I have a list with a bunch of dynamic elements. I would like to change the way they order themselves.
Here is what I have:
ul {
display: grid;
grid-template-columns: 1fr 1fr;
}
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
<li>I</li>
<li>J</li>
</ul>
and here is my expected result:
I could achieve that with:
ul {
grid-auto-flow: column;
grid-template-rows: repeat(5, 1fr);
}
but note the 5 here is troublesome because this magic number is half the size of the number of li. Is there any way to make it work dynamically? To make it work with any number of li?
I also try to play with order on li without success. Something with:
li:nth-child(even) {
order: 1; /* or -1 etc. */
}
I am looking for a CSS solution. I don’t want to rely with JS or by altering the HTML.
>Solution :
column-count should do the trick:
ul {
column-count: 2;
}
Try it:
// Demo only
const ul = document.querySelector('ul');
const numberOfLis = Math.random() * 20 + 5 | 0;
for (let i = 0; i < numberOfLis; i++) {
const li = document.createElement('li');
li.textContent = i;
ul.appendChild(li);
}
ul {
column-count: 2;
}
<ul></ul>
