Using auto-fill or auto-fit in grid-template-rows: repeat(auto-fill, 200px) only sets the height for the first row - why is this?

Viewed 3558

I wanted to set the row height for each row in a grid using grid-template-rows: repeat(auto-fill, 200px) but realised it only applies to the first row of the grid. Turns out grid-auto-rows: 200px was better suited for my needs, but I'd still like to know why using auto-fill in grid-template-rows: repeat(auto-fill, 200px) only sets the height for the first rows instead of all rows. Note: if I use an integer instead of auto-fill it correctly sets the height for the number of specified rows.

Image examples:

2 Answers

From the specfication:

When auto-fill is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container (treating each track as its max track sizing function if that is definite or as its minimum track sizing function otherwise, and taking gap into account); if any number of repetitions would overflow, then 1 repetition. Otherwise, if the grid container has a definite min size in the relevant axis, the number of repetitions is the smallest possible positive integer that fulfills that minimum requirement. Otherwise, the specified track list repeats only once.

It's a bit tricky but auto-fill is suitable for column definition because we have a max size since by default the element will be full width but it's not the case when dealing with row and height.

Unless you define an explicit height, you will most probably fall into the case of only one repetition like you are facing:

.container {
  display:grid;
  grid-template-rows:repeat(auto-fill,200px);
  grid-gap:5px;
}

.container div {
   height:50px;
   background:red;
}

body {
  border:5px solid blue;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

The same will happen in a column definition when using inline-grid

.container {
  display:inline-grid;
  grid-template-columns:repeat(auto-fill,200px);
  grid-gap:5px;
}

.container div {
   height:50px;
   background:red;
}
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

As you already noticed, the correct way is to use grid-auto-rows: 200px

So upon my inspection, I realized that this occur because the height of the parent is not sufficient for every row to be at least 200px. Make sure element have sufficient height and use auto-fit it worked for me.

Related