Grid Template Areas
grid-template-areas lets you describe your layout visually using ASCII-art-like named regions. Items are then placed by name rather than coordinates β making layouts extremely readable.
1. Defining Named Areas
Each string in grid-template-areas represents a row. Each word represents a cell, and the same word repeated means the area spans those cells. Use a dot (.) for an empty cell.
.container {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: 50px 1fr 40px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }2. Empty Cells with Dots
Use one or more dots (.) to leave a cell empty. The dots represent a cell that is not assigned to any named area.
.container {
grid-template-areas:
"a . b" /* col 2 is empty */
". c ." /* col 1 & 3 empty */
"d d d"; /* d spans full row */
}
/* . means: empty cell (no area assigned) */3. The Holy Grail Layout
A classic web layout: header, three columns (nav, main, aside), and a footer. With grid-template-areas this is straightforward.
.holy-grail {
display: grid;
grid-template-columns: 200px 1fr 180px;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
min-height: 100vh;
}4. Responsive Areas with Media Queries
Redefine grid-template-areas in media queries to completely restructure the layout for different screen sizes β just by reassigning area names.
.layout {
grid-template-columns: 200px 1fr;
grid-template-areas:
"header header"
"nav main"
"footer footer";
}
@media (max-width: 600px) {
.layout {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"nav"
"main"
"footer";
}
}5. grid-template Shorthand
grid-template combines grid-template-rows / grid-template-columns, with optional area definitions inline using a special syntax.
.container {
grid-template:
"head head" 50px
"side body" 1fr
/ 120px 1fr; /* column sizes after the slash */
}
/* Same as: */
.container {
grid-template-areas: "head head" "side body";
grid-template-rows: 50px 1fr;
grid-template-columns: 120px 1fr;
}