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
I don’t know if such a thing exists, but I take the following approach in these situations:
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 theli
. See this CodePen.