4

I'm working with some items in a list:

<ul>
  <li>Item1</li>
  <li>Item2</li>
  <li>Item3</li>
  <li>Item4</li>
  <li>Item5</li>
  <li>Item6</li>
  <li>Item7</li>
  <li>Item8</li>
</ul>

and I'm trying to get them to break into two columns using flexbox, which gives the result of this:

+--------------------+
|                    |
| Item1       Item2  |
|                    |
| Item3       Item4  |
|                    |
| Item5       Item6  |
|                    |
| Item7       Item8  |
|                    |
+--------------------+

But I'm trying to sort them in ascending order so it appears like this:

+--------------------+
|                    |
| Item1       Item5  |
|                    |
| Item2       Item6  |
|                    |
| Item3       Item7  |
|                    |
| Item4       Item8  |
|                    |
+--------------------+

Not sure how to achieve that by using CSS + Flexbox unless I need to add some JS into the mix?

Here's a demo on Codepen:

https://codepen.io/ultraloveninja/pen/drKLzG

kukkuz
  • 41,512
  • 6
  • 59
  • 95
ultraloveninja
  • 1,969
  • 5
  • 27
  • 56

4 Answers4

5

Use a column flexbox and set a height for the ul - see demo below:

ul {
  list-style: none;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  width: 100%;
  max-width: 150px;
  height: 8em;
}

li {
  margin: 5px;
}
<ul>
  <li>Item1</li>
  <li>Item2</li>
  <li>Item3</li>
  <li>Item4</li>
  <li>Item5</li>
  <li>Item6</li>
  <li>Item7</li>
  <li>Item8</li>
</ul>

Or you can use CSS columns - see demo below:

ul {
  list-style: none;
  columns: 2; /* added this */
  width: 100%;
  max-width: 150px;
  height: 8em;
}

li {
  margin: 5px;
}
<ul>
  <li>Item1</li>
  <li>Item2</li>
  <li>Item3</li>
  <li>Item4</li>
  <li>Item5</li>
  <li>Item6</li>
  <li>Item7</li>
  <li>Item8</li>
</ul>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
2

You can try to add a height / max height and change the direction to column or you can use the column rule:

ul {
  list-style:none;
  display: flex;
  flex-direction:column;
  flex-wrap:wrap;
  width: 100%;
  max-width: 150px;
  max-height: 130px;
}

or:

ul {
    -webkit-columns: 2;
    -moz-columns: 2;
    columns: 2;
}
Alessio
  • 3,404
  • 19
  • 35
  • 48
1

This solution from above worked best for me:

ul {
   -webkit-columns: 2;
   -moz-columns: 2;
   columns: 2;
}
MsDacia
  • 11
  • 3
  • duplicate of https://stackoverflow.com/a/55225438/ or else it should have been posted as a comment. – karel May 07 '22 at 10:13
0

I assume you are using the flexbox so that the container will expand width-wise to contain as many as possible items horizontally; in this case, flex-direction:column will not work. You may check out https://www.w3schools.com/css/css3_multiple_columns.asp

Support is skimpy, but it's the only thing that can do what you want (that's why it needed to be introduced): https://caniuse.com/#search=column

Dinu
  • 1,374
  • 8
  • 21