Search code examples
csscss-grid

Set "max rows" in grid-template-rows: repeat()


ul {
  display: grid;
  grid-template-rows: repeat(4, 2em);
  grid-auto-flow: column;
  column-gap: 1em;
}

li {
  list-style: none;
}
<hr>
<ul>
  <li>X</li>
  <li>X</li>
</ul>
<hr>
<ul>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
  <li>Y</li>
</ul>
</hr>

In this code I have a list with grid-template-rows: repeat(4, 2em);.

This fills the first column until the fourth row and then starts the second column. This is good.

The problem I have is that, when I have less than 4 items, the grid is still 4 rows tall. Is there a way to make the grid grow until the fourth row and then start adding columns?

Something like grid-template-rows: repeat(max 4, 2em).


Solution

  • Not naturally (see this Q&A).

    You can cheat though by defining a maximum number of rows and setting the height of the rows to auto and moving the actual height definition to the li. See this CodePen.

    ul {
      display: grid;
      grid-template-rows: repeat(4, auto);
      grid-auto-flow: column;
      column-gap: 1em;
      row-gap: 0.25em;
      border: 1px solid green;
      margin: 0;
      padding: 0;
    }
    
    li {
      list-style: none;
      height: 1.2em;
      background: lightblue;
    }
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
    </ul>
    <hr>
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
      <li>Item 5</li>
      <li>Item 6</li>
      <li>Item 7</li>
      <li>Item 8</li>
      <li>Item 9</li>
    </ul>
    </hr>