skip to Main Content
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).

2

Answers


  1. I don’t know if such a thing exists, but I take the following approach in these situations:

    .grid-4-column{
          grid-template-rows: repeat(4, 2em);
        }
        .grid-3-column{
          grid-template-rows: repeat(3, 2em);
        }
        .grid-2-column{
          grid-template-rows: repeat(2, 2em);
        }
    <ul class="grid-2-column">
      <li>X</li>
      <li>X</li>
    </ul>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search