Learn how to use named grid areas to create intuitive, readable page layouts with CSS Grid. Master grid-template-areas, the grid-area shorthand, and responsive layout techniques.
CSS Grid's grid-template-areas property lets you define your layout using named regions instead of line numbers. Each string represents a row, and each name within that string represents a column cell. This creates a visual map of your layout right in the CSS.
.layout {
display: grid;
grid-template-areas:
"header header header"
"sidebar main main"
"footer footer footer";
grid-template-rows: 60px 1fr 40px;
grid-template-columns: 200px 1fr 1fr;
}Rules for grid-template-areas:
.) to represent an empty cell.This approach is arguably the most readable way to define layouts in CSS.
<style>
.page {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-rows: 60px 1fr 40px;
grid-template-columns: 200px 1fr;
min-height: 300px;
gap: 8px;
}
.header { grid-area: header; background: #6366f1; }
.sidebar { grid-area: sidebar; background: #8b5cf6; }
.main { grid-area: main; background: #1e293b; }
.footer { grid-area: footer; background: #6366f1; }
</style>
<div class="page">
<div class="header">Header</div>
<div class="sidebar">Sidebar</div>
<div class="main">Main Content</div>
<div class="footer">Footer</div>
</div>One of the most powerful aspects of named grid areas is how easy they make responsive design. You can completely rearrange the layout by simply redefining the grid-template-areas in a media query without changing any HTML.
/* Mobile: single column */
.page {
display: grid;
grid-template-areas:
"header"
"main"
"sidebar"
"footer";
grid-template-columns: 1fr;
}
/* Desktop: two columns */
@media (min-width: 768px) {
.page {
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
}
}Notice how the sidebar moves from below the main content on mobile to beside it on desktop. The HTML order stays the same, but the visual layout changes entirely. This separation of content order from visual order is a core strength of CSS Grid.
You can also use dots (.) for empty cells:
grid-template-areas:
". header ."
". main ."
". footer .";Which of the following is an INVALID grid-template-areas definition?