Simple Solution for Equal Height Grid Rows
To create a grid with rows of equal height, where the tallest cell sets the height for all rows, you can use the following quick and straightforward solution:
- Set the container to
grid-auto-rows: 1fr
Explanation of the Solution
In Grid Layout, the fr
unit is used to establish flexible lengths in a grid container. This unit distributes free space in the container, similar to the flex-grow
property in flexbox.
By setting all rows in a grid container to 1fr
:
grid-auto-rows: 1fr;
All rows will have equal height. This concept may seem contradictory at first, but the behavior is defined in the grid specification.
The grid spec states that when dealing with dynamically-sized grids (e.g., indefinite height), the rows are sized according to their contents. The height of each row is determined by the tallest item in that row.
By setting the rows to 1fr
, the height of each row becomes the length of the tallest row. This is how 1fr
creates rows of equal height in a grid container.
Why Flexbox is Not Suitable for Equal Height Rows
Unlike Grid Layout, flexbox does not support equal height rows across multiple rows. In a flex container with multiple lines, each line's height is the minimum necessary to contain the flex items on that line.
This behavior is defined in the flexbox specification, making Grid Layout the better option for achieving equal height rows in a grid container.