包装后将弹性项目保持在适当的列中

Keep flex items in proper columns after wrapping

我正在尝试使用 justify-content 来正确调整容器内的 divs,但是这个选项没有按我预期的方式工作。我希望容器内的 div 在示例的第二行保持顺序,如下所示:

1   2   3
4   5

不喜欢:

1  2  3
4     5

.container {
  display: flex;
  width: 1100px;
  justify-content: space-between;
  flex-wrap: wrap;
}
.container > div {
  width: 330px;
  height: 125px;
  background-color: rgba(18, 28, 41, 0.50);
  border: 1px solid #325E82;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

代码笔:https://codepen.io/anon/pen/pryWYZ

一种解决方案是使用伪选择器 ::after 来创建一个假 'invisible' 元素,该元素与其他元素占用相同的宽度。结合 justify-content,这会导致现有的最终元素移动到中心:

.container {
  display: flex;
  width: 1100px;
  justify-content: space-between;
  flex-wrap: wrap;
}

.container > div {
  width: 330px;
  height: 125px;
  background-color: rgba(18, 28, 41, 0.50);
  border: 1px solid #325E82;
}

.container::after {
  content: '';
  width: 332px; /* .container > div 'width' plus .container > div 'border' */
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

我还创建了这个 here.

的 CodePen

希望对您有所帮助! :)

另一种方法是在 .Container 上设置 justify-content: flex-start; 并根据所需的数量在 correct Child 项目上指定边距列并限制孩子的大小。

对于 3 列网格,如下所示:

.container {
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}

.item {
  background-color: gray;
  width: 100px;
  height: 100px;
  flex: 0 0 32%;
  margin: 1% 0;
  
  }
  
  .item:nth-child(3n-1) {
    margin-left: 2%;
    margin-right: 2%;
  }
  
<div class="container">
  <div class=item></div>
  <div class=item></div>
  <div class=item></div>
  <div class=item></div>
  <div class=item></div>
   
</div>

Flexbox 并不是为了创建完美的网格而设计的。这就是为什么对齐最后一行的弹性项目没有自然的解决方案。您需要技巧才能使其发挥作用。

这在这些 post 中有详细解释:

  • Is it possible for flex items to align tightly to the items above them?

解决这个问题的理想方法是从弹性布局切换到网格布局。使用 CSS 网格布局,可以更好地控制内容项的位置和大小。

.container {
  display: grid;
  grid-auto-rows: 125px;
  grid-template-columns: repeat(auto-fill, 330px);
  grid-gap: 10px;
  width: 1100px;
}

.container>div {
  background-color: rgba(18, 28, 41, 0.50);
  border: 1px solid #325E82;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

有关 CSS 网格的更多详细信息,包括对上述属性的解释和浏览器支持数据,请参阅此 post:CSS-only masonry layout but with elements ordered horizontally