使flex项目换行以创建新列

时间:2017-07-26 21:07:07

标签: html css css3 flexbox css-grid

我在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>

1 个答案:

答案 0 :(得分:2)

您需要在容器上设置高度。否则,flex项目将如何知道包装的位置?

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>

备注:Remove space (gaps) between multiple lines of flex items when they wrap

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 Grid

这是使用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>