CSS Grid Template Areas
Also Known As
TL;DR
Explanation
Grid template areas use ASCII art to define a layout visually in CSS. The `grid-template-areas` property on the container accepts a string per row, with each word representing one grid cell. Repeated words span multiple cells. A dot (`.`) represents an empty cell. Child elements are assigned to areas using `grid-area: name`. This approach decouples the visual layout from the DOM order and column/row counting, making it easy to create responsive layouts by redefining areas at breakpoints. Unlike `grid-column: 2 / 4` shorthand, area names are self-documenting. The feature also implicitly defines `grid-template-rows` and `grid-template-columns` line names based on area boundaries — each area creates `-start` and `-end` named lines automatically.
Diagram
flowchart TD
subgraph grid-template-areas
H[header header header]
S[sidebar main aside]
F[footer footer footer]
end
subgraph Mobile breakpoint
MH[header]
MM[main]
MS[sidebar]
MA[aside]
MF[footer]
end
style H fill:#1f6feb,color:#fff
style F fill:#238636,color:#fff
style MH fill:#1f6feb,color:#fff
style MF fill:#238636,color:#fff
Common Misconception
Why It Matters
Common Mistakes
- Defining a non-rectangular area — grid template areas must always form a rectangle; an L-shape or T-shape is invalid and silently ignored.
- Mismatching the number of columns across rows — every row string must define the same number of cells.
- Using the same area name in non-contiguous cells — an area must be a single contiguous rectangle.
- Forgetting to set `display: grid` on the parent before using `grid-template-areas`.
Code Examples
/* Hard to read — pure column/row numbers */
.layout {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: 60px 1fr 40px;
}
.header { grid-column: 1 / 4; grid-row: 1; }
.sidebar { grid-column: 1; grid-row: 2; }
.main { grid-column: 2; grid-row: 2; }
.aside { grid-column: 3; grid-row: 2; }
.footer { grid-column: 1 / 4; grid-row: 3; }
/* Self-documenting with named areas */
.layout {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: 60px 1fr 40px;
grid-template-areas:
'header header header'
'sidebar main aside'
'footer footer footer';
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.aside { grid-area: aside; }
.footer { grid-area: footer; }
/* Responsive: redefine areas at breakpoint */
@media (max-width: 768px) {
.layout {
grid-template-columns: 1fr;
grid-template-areas:
'header'
'main'
'sidebar'
'aside'
'footer';
}
}