Search code examples
csscss-grid

Changing the order of items in a CSS grid from left-right to top-down


I'm building a list of tags in a system, and those tags should be displayed in a CSS grid with three columns. So, something like this:

<ul>
    <li>Alfa</li>
    <li>Bravo</li>
    <li>Charlie</li>
    <li>Delta</li>
    <li>Echo</li>
    <li>Foxtrot</li>
</ul>
ul {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
}

When viewing this in a browser, the items are ordered like this:

Alfa  Bravo Charlie
Delta Echo  Foxtrot

However, i would like them to be ordered like this:

Alfa  Charlie Echo
Bravo Delta   Foxtrot

So, basically ordered from top to bottom instead of left-right.

Is there any way to do this in a simple way? I already experimented a bit with :nth-child selectors and grid-column, but that doesn't really do what i want. I could probably solve this with Javascript, but i like to know if there's a CSS-only solution.


Solution

  • I would recommend that you use columns instead of grid columns for this

    ul{
      columns: 3
    }
    <ul>
        <li>Alfa</li>
        <li>Bravo</li>
        <li>Charlie</li>
        <li>Delta</li>
        <li>Echo</li>
        <li>Foxtrot</li>
    </ul>

    Have a great day!