Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reorder a grid component from column to row?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading