I'm working with a CSS Grid layout and trying to evenly distribute rows inside a fixed-height container using:
grid-template-rows: repeat(auto-fit, minmax(100px, 1fr));
Here’s the full CSS and minimal HTML:
.container {
height: 600px;
width: 500px;
margin: 200px auto;
background-color: black;
box-shadow: 0 6px 20px rgb(0 0 0 / 0.2);
display: grid;
grid-auto-flow: row;
grid-template-rows: repeat(auto-fit, minmax(100px, 1fr));
}
.box {
color: white;
font-size: 1.5rem;
text-align: center;
}
<body>
<div class="container">
<div class="box" style="background-color: #e53935">FIRST</div>
<div class="box" style="background-color: #d81b60">SECOND</div>
<div class="box" style="background-color: #8e24aa">THIRD</div>
<div class="box" style="background-color: #5e35b1">FOURTH</div>
<div class="box" style="background-color: #3949ab">FIFTH</div>
<div class="box" style="background-color: #1e88e5">SIXTH</div>
<div class="box" style="background-color: #00acc1">SEVENTH</div>
<div class="box" style="background-color: #00897b">EIGHTH</div>
</div>
</body>
The container has a fixed height of 600px
and contains 8 items. Since each row uses minmax(100px, 1fr)
, I expected each of the 8 rows to get at least 100px.
However, the last two items (SEVENTH and EIGHTH) are only getting about 27px height each. Why is this happening?
Because grid-template-rows
with repeat(auto-fit, ...)
will calculate the MAXIMUM grid row tracks (explicit grid rows) based on the grid size.
With your set up (600px grid size with minimum 100px fragment size), it can fit 6 rows at most since it's the maximum items it can fit without overflowing. Everything after the 6th element will be put in implicitly-created grid row tracks, which the size is not controled by grid-template-rows
, so to them the size restriction is ignored.
To fix this, you could add grid-auto-rows: minmax(100px, 1fr)
, so the implicitly-created grid row tracks will have the same size restriction as explicit ones. Also, you may remove grid-template-rows
all together that it's redundant with this layout.
.container {
height: 600px;
width: 500px;
margin: 200px auto;
background-color: black;
box-shadow: 0 6px 20px rgb(0 0 0 / 0.2);
display: grid;
grid-auto-flow: row;
grid-template-rows: repeat(auto-fit, minmax(100px, 1fr));
grid-auto-rows: minmax(100px, 1fr);
}
.box {
color: white;
font-size: 1.5rem;
text-align: center;
}
<body>
<div class="container">
<div class="box" style="background-color: #e53935">FIRST</div>
<div class="box" style="background-color: #d81b60">SECOND</div>
<div class="box" style="background-color: #8e24aa">THIRD</div>
<div class="box" style="background-color: #5e35b1">FOURTH</div>
<div class="box" style="background-color: #3949ab">FIFTH</div>
<div class="box" style="background-color: #1e88e5">SIXTH</div>
<div class="box" style="background-color: #00acc1">SEVENTH</div>
<div class="box" style="background-color: #00897b">EIGHTH</div>
</div>
</body>