2

I'm populating elements in a div, and I want to arrange them so it would be like this:

1 3
2 4

Right now, it's just going down

1
2
3
4

How do I tell it to move to the next column after 2 elements?

.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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
hellomello
  • 8,219
  • 39
  • 151
  • 297

1 Answers1

3

You need to set a height on the container. Otherwise, how will the flex items know where to wrap?

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>

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


order

Alternatively, if you don't want to set a height on the container, you can use the order property.

.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

Here's another way using CSS Grid Layout:

.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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701