如何在flexbox中为较小的屏幕包装项目?

时间:2016-05-13 19:45:38

标签: html css css3 flexbox

我正在尝试为不同的调整大小创建布局。我需要在这些图片中找到结果:

flexbox result

我有这段代码:



.container {
  position: relative;
  display: flex;
  align-items: stretch;
}
.item {
  background-color: black;
  box-sizing: border-box;
  padding: 20px;
  flex: 2;
  color: #fff;
}
.item:nth-child(2) {
  background-color: grey;
  flex: 1
}
.item:nth-child(3) {
  background-color: green;
  flex: 0.5;
}
@media screen and (max-width: 990px) {
  .container {
    height: auto;
    display: table;
  }
  .item:nth-child(2) {
    float: left;
  }
  .item:nth-child(3) {
    float: right;
  }
}

<section class="container">
  <div class="item">
    <h2>title1</h2>
    <hr>You'll notice that even though this column has far more content in it, instead of the other columns ending early, they size themselves to meet the end of this column vertically.</div>
  <div class="item">
    <h2>title2</h2>
    <hr>Normally, the only way to achieve this would be either a hack, or to set all boxes to min-height.
  </div>
  <div class="item">
    <h2>title3</h2>
    <hr>This is a column with not much content.
  </div>
</section>
&#13;
&#13;
&#13;

这里有一个codepen https://codepen.io/darudev/pen/pyBrzL

问题在990px​​调整大小视图中,我找不到创建与&#34;模拟&#34;相同视图的解决方案。

有人可以帮助我或给我一些建议吗?

谢谢。

1 个答案:

答案 0 :(得分:13)

您的代码中不需要table和float属性。

@media screen and (max-width: 990px) {
  .container {
    height: auto;
    display: table;
  }
  .item:nth-child(2) {
    float: left;
  }
  .item:nth-child(3) {
    float: right;
  }
}

可以使用flexbox进行整个布局。

以下是解决方案:当屏幕调整大小小于990像素时,允许弹性项目换行并为第一个项目提供100%宽度,这会强制将下列项目放到下一行。

.container {
  display: flex;
}

.item {
  background-color: black;
  box-sizing: border-box;
  padding: 20px;
  flex: 2;
  color: #fff;
}

.item:nth-child(2) {
  background-color: grey;
  flex: 1;
}

.item:nth-child(3) {
  background-color: green;
  flex: 0.5;
}

@media screen and (max-width:990px) {
  .container { flex-wrap: wrap;  }
  .item:first-child { flex-basis: 100%; }
}
<section class="container">
  <div class="item">
    <h2>title1</h2>
    <hr>You'll notice that even though this column has far more content in it, 
         instead of the other columns ending early, they size themselves to meet the end
         of this column vertically.</div>
  <div class="item">
    <h2>title2</h2>
    <hr>Normally, the only way to achieve this would be either a hack, or to set
        all boxes to min-height.</div>
  <div class="item">
    <h2>title3</h2>
    <hr>This is a column with not much content.
  </div>
</section>

revised codepen