0
0
CssHow-ToBeginner · 4 min read

How to Use grid-template-rows in CSS for Row Layouts

Use 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
css
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.

css
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;
}
Output
<div class="container"> <div class="item1">Row 1 (100px tall)</div> <div class="item2">Row 2 (2 fractions of space)</div> <div class="item3">Row 3 (auto height)</div> </div>
⚠️

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:

css
.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

ValueMeaningExample
Fixed row height100px, 5rem
Percentage of container height50%
Fraction of available space1fr, 2fr
autoRow height fits contentauto
min-contentRow shrinks to smallest contentmin-content
max-contentRow grows to largest contentmax-content

Key Takeaways

Use grid-template-rows to set row heights in a CSS grid container.
You can mix fixed units, fractions, and auto to create flexible layouts.
Ensure the number of row sizes matches your grid structure to avoid layout issues.
Fraction units (fr) divide leftover space proportionally among rows.
Avoid fixed heights for all rows to keep your design responsive.