使弹性项目换行以创建新列

Make flex items wrap to create a new column

我正在 div 中填充元素,我想这样排列它们:

1 3
2 4

现在,它正在下降

1
2
3
4

如何让它在 2 个元素之后移动到下一列?

.parent {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

您需要在容器上设置高度。否则,弹性项目怎么知道在哪里换行?

height

.parent {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: flex-start; /* see notes */
  height: 50px;
}

.item {
  height: 25px;
}
<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

备注:


order

或者,如果您不想在容器上设置高度,您可以使用 order 属性.

.parent {
  display: inline-flex;
  flex-wrap: wrap;
}

.item {
  flex: 0 0 50%;
}

.item:nth-child(1) { order: 1; }
.item:nth-child(2) { order: 3; }
.item:nth-child(3) { order: 2; }
.item:nth-child(4) { order: 4; }
<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>

CSS 网格

这是使用 CSS 网格布局的另一种方法:

.parent {
  display: inline-grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 25px 25px;
  grid-auto-flow: column;
  grid-gap: 5px;
}
<div class="parent">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
</div>