Search code examples
csscss-grid

CSS Grid vertical columns with infinite rows


I have a list of items of unknown length (from a CMS). I want to display them in 2 vertical columns reading down. e.g.

1 4
2 5
3 6

etc...

I am trying to achieve this with CSS grid, however, it doesn't seem possible unless you set the number of rows up front. I have tried grid-auto-flow: column as per https://gridbyexample.com/examples/example18/ but this just adds additional columns when it gets to the end.

I feel like this should be possible with grid, but I can't find a way. Anyone have any ideas?

P.S. Please don't suggest CSS text columns.


Solution

  • Without knowing the exact amount of items this is not possible with CSS grid alone.

    The only way to get around this limitation is to add a class to your second half of the items.

    body {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-auto-flow: row dense;
      
      /* extra styles */
      grid-gap: 0.5rem;
    }
    
    span {
      grid-column-start: 1;
      
      /* extra styles */
      background-color: #def;
      padding: 0.5rem;
    }
    
    .second-half {
      grid-column-start: 2;
      
      /* extra styles */
      background-color: #abc;
    }
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
    <span class="second-half">5</span>
    <span class="second-half">6</span>
    <span class="second-half">7</span>