在宽浏览器上实现6行,然后使用Flexbox在移动宽度上实现2列,3行

时间:2017-05-14 05:10:17

标签: html css flexbox

我创建了一个小提琴https://jsfiddle.net/mh4moyzy/并且我不确定我需要添加什么,以便当浏览器的宽度大于400px的移动宽度时,使所有这些框堆叠成行和浏览器宽度一样宽。这意味着将有6行和1列。在移动设备中,将有3行和2列。



 .flex-container {
      padding: 0;
      margin: 0;
      list-style: none;
      display: -webkit-box;
      display: -moz-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
      -webkit-flex-flow: row wrap;
      justify-content: space-around;
    }
    .flex-item {
      background: tomato;
      padding: 5px;
      width: 200px;
      height: 150px;
      margin-top: 10px;
      line-height: 150px;
      color: white;
      font-weight: bold;
      font-size: 3em;
      text-align: center;
  }
 

    <ul class="flex-container">
      <li class="flex-item">1</li>
      <li class="flex-item">2</li>
      <li class="flex-item">3</li>
      <li class="flex-item">4</li>
      <li class="flex-item">5</li>
      <li class="flex-item">6</li>
    </ul>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您应该使用媒体查询。对于制作弹性项目,取所有宽度并按列方向添加此代码

@media (min-width: 400px) {
  .flex-container {
    flex-direction: column;
  }

  .flex-item {
    width: auto;
  }
}

此外,如果您希望手机中始终有2列,则可以将此样式添加到.flex-item

width: calc(50% - 10px);
box-sizing: border-box;

所以示例如下:

&#13;
&#13;
.flex-container {
    padding: 0;
    margin: 0;
    list-style: none;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-flow: row wrap;
    justify-content: space-around;
}
.flex-item {
    background: tomato;
    padding: 5px;
    width: calc(50% - 10px); /* replacing fixed width with percentage */
    height: 150px;
    margin-top: 10px;
    line-height: 150px;
    color: white;
    font-weight: bold;
    font-size: 3em;
    text-align: center;
    box-sizing: border-box; /* Setting borders and paddings to be considered part of width */
}

@media (min-width: 400px) {
  .flex-container {
    flex-direction: column;
  }
  
  .flex-item {
    width: auto;
  }
}
&#13;
<ul class="flex-container">
    <li class="flex-item">1</li>
    <li class="flex-item">2</li>
    <li class="flex-item">3</li>
    <li class="flex-item">4</li>
    <li class="flex-item">5</li>
    <li class="flex-item">6</li>
</ul>
&#13;
&#13;
&#13;