4

With flexbox, how do I make a list of items span over two columns?

For example:

2 toyota
1 mazda
8 audi
4 nissan
7 bmw
9 lexus

The above would be:

2 toyota        7 bmw   
1 mazda         9 lexus
8 audi
4 nissan

HTML:

<div class="container">
  <div class="item">2 toyota</div>
  <div class="item">1 mazda</div>
  <div class="item">8 audi</div>
  <div class="item">4 nissan</div>
  <div class="item">7 bmw</div>
  <div class="item">9 lexus</div>
</div>

CSS:

.container {
   display: flex;
   flex-direction: column;
   height: 200px;
}

Do I need to use a flex-basis on the item class? How do I get the rest of the items from the list displayed on another column?

Asons
  • 84,923
  • 12
  • 110
  • 165
userden
  • 1,615
  • 6
  • 26
  • 50

1 Answers1

4

The ìtem's will wrap into to a new column when there is no space left for all to fit, so in this case, to force a break after the 4th, give them a 50px height.

Also, for them to be allowed to wrap, you also need to add flex-wrap: wrap.

.container {
   display: flex;
   flex-direction: column;
   flex-wrap: wrap;
   height: 200px;
}
.container .item {
  flex-basis: 50px;
}
<div class="container">
  <div class="item">2 toyota</div>
  <div class="item">1 mazda</div>
  <div class="item">8 audi</div>
  <div class="item">4 nissan</div>
  <div class="item">7 bmw</div>
  <div class="item">9 lexus</div>
</div>

Here is a great post dealing with possible future issues:

Asons
  • 84,923
  • 12
  • 110
  • 165