Topic 49 of 62
Template Areas
Overview
Manually counting grid lines (grid-column: 2 / 4) is highly prone to human error and difficult to read. grid-template-areas is a magical feature that allows you to physically 'draw' your layout using ASCII art (plain text strings). You assign names to the children, and then literally map out where those names go in a visual grid representation. It makes complex layouts instantly readable to any developer.
Syntax
css
/* 1. Assign names to the children */
.logo { grid-area: hd; } /* Header */
.nav { grid-area: sd; } /* Sidebar */
.content { grid-area: mn; } /* Main */
.footer { grid-area: ft; } /* Footer */
/* 2. Draw the layout on the Parent! */
.app-layout {
display: grid;
/* 3 columns, 3 rows */
grid-template-columns: 200px 1fr 100px;
grid-template-rows: 60px 1fr 40px;
/* Draw the map using the names! */
grid-template-areas:
"hd hd hd" /* Header spans all 3 columns */
"sd mn mn" /* Sidebar on left, Main spans 2 columns */
"ft ft ft"; /* Footer spans all 3 columns */
}Common Pitfalls
- Drawing non-rectangular areas.
grid-template-areasstrictly requires every named area to form a perfect rectangle. You cannot make an 'L' shape or a 'T' shape. If you try, the browser will instantly invalidate the entire CSS rule. - Misspelling a name or having an unequal number of columns in the strings. Every string MUST have the exact same number of columns. If one string has 3 words and another has 2, the entire layout crashes.
Interview Questions
Q:
How do you leave an 'empty' cell in a
grid-template-areas ASCII layout?A:
You use a dot/period (.). For example, "sd mn ." leaves the 3rd column completely empty.
Real-World Example
Completely rearranging a complex dashboard layout for mobile devices simply by redrawing the ASCII art map, touching zero HTML.
example
css
/* Desktop */
.dashboard {
grid-template-areas:
"nav main stats"
"nav main stats";
}
/* Mobile (Stack everything vertically!) */
@media (max-width: 768px) {
.dashboard {
grid-template-areas:
"nav"
"stats"
"main";
}
}Check Your Knowledge
Test your understanding of Template Areas with these quick questions.