Grid Template Areas
Name regions to build layouts visually.
Syntax
grid-template-areas: "header header" "nav main";grid-template-areas lets you name areas of a grid and place items by name. It reads like a picture of your layout.
Each string is a row, and repeated names make an item span multiple cells. Assign an item to an area with grid-area.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer names grid regions (header, sidebar, main, footer) so the layout is readable as ASCII art directly in the CSS.
- A designer swaps a sidebar from the left to the right in a layout by editing only the grid-template-areas string, without changing HTML.
- A developer redefines grid-template-areas in a media query so a three-column desktop layout collapses to a single column on mobile.
More examples
Named areas for page layout
Defines the entire page structure as an ASCII-art grid and assigns each element with grid-area.
.page {
display: grid;
grid-template-columns: 240px 1fr;
grid-template-rows: 60px 1fr 40px;
grid-template-areas:
'header header'
'sidebar main '
'footer footer';
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }Swapping sidebar side via areas
Moves the sidebar from left to right purely by rewriting the grid-template-areas and column order.
/* Sidebar on the left */
.page {
grid-template-columns: 240px 1fr;
grid-template-areas:
'sidebar main';
}
/* Sidebar on the right β no HTML change */
.page.right-sidebar {
grid-template-columns: 1fr 240px;
grid-template-areas:
'main sidebar';
}Responsive area collapse to mobile
Defines a mobile-first single-column area layout that expands to a two-column layout on wider screens.
.page {
display: grid;
grid-template-areas:
'header'
'main'
'sidebar'
'footer';
}
@media (min-width: 900px) {
.page {
grid-template-columns: 240px 1fr;
grid-template-areas:
'header header'
'sidebar main'
'footer footer';
}
}
Discussion