'Flexbox columns in ascending order
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:
Solution 1:[1]
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>
Solution 2:[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;
}
Solution 3:[3]
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
Solution 4:[4]
This solution from above worked best for me:
ul {
-webkit-columns: 2;
-moz-columns: 2;
columns: 2;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kukkuz |
Solution 2 | Alessio |
Solution 3 | Dinu |
Solution 4 | MsDacia |