How to Use grid-template-rows in CSS for Row Layouts
grid-template-rows in CSS to set the height of rows in a grid container. You list sizes separated by spaces, like grid-template-rows: 100px 200px auto;, which means the first row is 100 pixels tall, the second 200 pixels, and the third adjusts automatically.Syntax
The grid-template-rows property defines the height of each row in a CSS grid container. You specify one or more sizes separated by spaces. Each size can be a length (like px, em), a percentage, fr units (fraction of available space), or keywords like auto.
- Length units: fixed height rows (e.g.,
100px) - Fraction units: flexible rows sharing space (e.g.,
1fr 2fr) - Auto: row height fits content
grid-template-rows: <row-size> [<row-size> ...];
Example
This example creates a grid with three rows: the first row is 100 pixels tall, the second row takes twice the remaining space, and the third row adjusts to its content height.
html, body {
height: 100%;
margin: 0;
}
.container {
display: grid;
grid-template-rows: 100px 2fr auto;
height: 300px;
border: 2px solid #333;
}
.item1 {
background-color: lightcoral;
}
.item2 {
background-color: lightblue;
}
.item3 {
background-color: lightgreen;
padding: 10px;
}Common Pitfalls
One common mistake is not matching the number of rows defined with the actual grid items or rows in the layout, which can cause unexpected sizing. Another is using fixed units everywhere, which can break responsiveness. Also, confusing fr units with pixels can lead to wrong assumptions about row sizes.
Example of a wrong and right way:
.container {
display: grid;
grid-template-rows: 100px 100px; /* Wrong if you have 3 rows */
}
/* Correct: define three rows or use auto for flexible rows */
.container {
display: grid;
grid-template-rows: 100px 100px auto;
}Quick Reference
| Value | Meaning | Example |
|---|---|---|
| Fixed row height | 100px, 5rem | |
| Percentage of container height | 50% | |
| Fraction of available space | 1fr, 2fr | |
| auto | Row height fits content | auto |
| min-content | Row shrinks to smallest content | min-content |
| max-content | Row grows to largest content | max-content |
Key Takeaways
grid-template-rows to set row heights in a CSS grid container.fr) divide leftover space proportionally among rows.