Overview
grid-template-areas names grid regions so items are placed by name instead of line numbers, and a breakpoint can restructure the layout by redefining one property. General grid concepts are in css-grid; track sizing units are in css-units.
Syntax
Name areas on the container, then place items with grid-area.
.layout {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 240px 1fr;
grid-template-rows: auto 1fr auto;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }| Rule | Detail |
|---|---|
| Each string is a row; each word is a column. | "a b" is one row with two columns. |
| Repeat a name to span cells. | "header header header" spans three columns. |
. is an empty cell. | One or more dots; no name. |
| Each area must be one rectangle. | "a b" "a a" (an L shape) invalidates the whole declaration. |
| Names are identifiers. | Letters, digits, -, _; no spaces. |
Shorthand
grid-template sets areas, row sizes, and column sizes together; row sizes follow each string, column sizes follow the slash.
.layout {
display: grid;
grid-template:
"header header" auto
"sidebar main" 1fr
"footer footer" auto
/ 240px 1fr;
}| Property | Note |
|---|---|
grid-area: header | Place by name. |
grid-area: 2 / 1 / 4 / 3 | Line-based: row-start / column-start / row-end / column-end. |
grid shorthand | Also resets the implicit track properties. |
Responsive layouts
Redefine only grid-template-areas and the track sizes; item rules stay unchanged.
.layout { grid-template-areas: "header" "main" "sidebar" "footer"; grid-template-columns: 1fr; }
@media (min-width: 768px) {
.layout {
grid-template-areas: "header header" "sidebar main" "footer footer";
grid-template-columns: 240px 1fr;
}
}Gotchas
Avoid these; each makes the browser drop or misplace an area.
| Gotcha | Fix |
|---|---|
A non-rectangular area drops the whole grid-template-areas value. | Keep every name in one rectangle. |
grid-area overrides earlier grid-row and grid-column on the same item. | Use one placement style per item. |
A . cell does not stop auto-placed items from landing there. | Place those items explicitly. |
gap adds to item margins. | Use one or the other for spacing. |
| Auto-fill card grids need no areas. | Use repeat(auto-fill, minmax(280px, 1fr)). |