The grid-template-rows
property specifies the number and height of the rows in a grid container. It works in the same way as grid-template-columns
but for the vertical axis.
Example 1: Using Pixels
/* Defines a grid with two rows of fixed height */
.grid-container {
display: grid;
/* The first row is 100px high, and the second is 200px high */
grid-template-rows: 100px 200px;
}
Explanation This sets up a grid with two rows having explicit heights. This is useful for design elements that require a specific vertical size.
Example 2: Using Percentages
/* Defines responsive row heights */
.grid-container {
display: grid;
height: 400px; /* A container height is needed for row percentages to work */
/* The first row takes 25% and the second 75% of the container's height */
grid-template-rows: 25% 75%;
}
Explanation When using percentages for grid-template-rows
, the grid container must have a defined height. The row heights will then be a percentage of this container height.
Example 3: Using Fractional Units (fr)
/* Defines flexible row heights */
.grid-container {
display: grid;
height: 300px;
/* The first row is twice the height of the second row */
grid-template-rows: 2fr 1fr;
}
Explanation The fr
unit distributes the available vertical space within the grid container among the rows. This allows rows to grow and shrink proportionally.
Example 4: Using the repeat() function
/* Defines three rows of equal height */
.grid-container {
display: grid;
height: 600px;
/* Creates three rows, each 200px high */
grid-template-rows: repeat(3, 200px);
}
Explanation The repeat()
function simplifies the creation of multiple rows with a uniform height, making the CSS cleaner and easier to read.
Example 5: Using minmax()
/* Defines a row with a minimum and maximum height */
.grid-container {
display: grid;
/* The row will have a minimum height of 50px and a maximum of auto */
grid-template-rows: minmax(50px, auto);
}
Explanation minmax()
for rows ensures that a row will never be smaller than the minimum value, but can grow to accommodate its content, up to the maximum value specified.
Example 6: Using the auto keyword
/* Defines row heights based on content */
.grid-container {
display: grid;
/* The first and third rows are fixed, the middle adapts to its content's height */
grid-template-rows: 50px auto 100px;
}
Explanation Using auto
for row height makes the row as tall as necessary to fit its content. This is ideal for dynamic content of varying lengths.
Example 7: Mixing Units
/* Defines a complex row structure with mixed units */
.grid-container {
display: grid;
height: 500px;
/* A combination of fixed, flexible, and content-based row heights */
grid-template-rows: 100px 1fr auto;
}
Explanation Combining different units for grid-template-rows
provides ultimate control over the vertical rhythm and structure of your grid, creating truly custom layouts.