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

Zar*_*bat 9 html css css3 flexbox

我正在尝试为不同的resize创建一个布局.我需要在这些图片中找到结果:

flexbox结果

我有这个代码:

.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;
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

问题是在990px​​调整大小视图中,我找不到解决方案来创建与"mockup"相同的视图.

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

谢谢.

Mic*_*l_B 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

这是解决方案:当屏幕调整大小小于990px​​时,允许弹性项目换行并为第一个项目提供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%; }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

修改后的codepen

  • 非常感谢@Michael_B:D! (2认同)