Grid Template Areas & Named Lines
Grid template areas let you define layouts using named regions — creating a visual ASCII-art map of your page. This makes complex layouts readable and maintainable. Named lines provide another way to precisely place items.
Template Areas Explained
- grid-template-areas — Define a visual layout map: 'header header' 'sidebar main' 'footer footer'
- grid-area — Assign an element to a named area: grid-area: header
- Each string is one row — Columns are separated by spaces within the string
- Repeat names for spanning — 'header header' makes header span 2 columns
- Use . for empty cells — 'sidebar main' / '. main' leaves the bottom-left cell empty
- Named lines — grid-template-columns: [sidebar-start] 250px [sidebar-end content-start] 1fr [content-end]
- Place items on named lines — grid-column: sidebar-start / content-end
Template Areas Code
/* Page layout with named areas */
.page {
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: 60px 1fr 50px;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
gap: 0;
}
.header { grid-area: header; background: #1a1a2e; }
.sidebar { grid-area: sidebar; background: #16213e; }
.main { grid-area: main; padding: 24px; }
.footer { grid-area: footer; background: #1a1a2e; }
/* Responsive: stack on mobile */
@media (max-width: 768px) {
.page {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"main"
"footer";
/* Sidebar hidden or moved */
}
.sidebar { display: none; }
}Tip
Grid template areas act as living documentation — the ASCII art in your CSS literally shows you the page layout. When you need to reorganize sections for mobile (e.g., move sidebar below main), you simply redraw the string map inside a media query — no moving HTML elements.
Grid handles two-dimensional layouts — rows AND columns simultaneously
Common Mistake
Area names in grid-template-areas must be consistent with grid-area values. A typo like grid-area: headers vs grid-template-areas: 'header header' means the element won't be placed. Also, every row in the template must have the same number of columns or the grid is invalid.
Practice Task
Build a full-page layout using grid-template-areas: (1) Define a grid with 'header header' / 'sidebar main' / 'footer footer', (2) Give each area a distinct background color, (3) Add a media query that collapses to a single column on mobile by redefining the template areas.
Quick Quiz
Key Takeaways
- Grid template areas let you define layouts using named regions — creating a visual ASCII-art map of your page.
- grid-template-areas — Define a visual layout map: 'header header' 'sidebar main' 'footer footer'
- grid-area — Assign an element to a named area: grid-area: header
- Each string is one row — Columns are separated by spaces within the string