How to Master CSS Grid Layout: A Visual Guide to Grid Template Areas
Traditional CSS Grid involves counting lines (grid-column: 1 / 3). It's powerful but hard to read. Enter Grid Template Areas: the ASCII art of Web Design.
Advertisement
The Concept
Instead of numbers, you give your cells names. It allows you to visualize your layout directly in the code.
.container {
display: grid;
grid-template-columns: 1fr 3fr 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"sidebar main ads"
"footer footer footer";
gap: 1rem;
}
Assigning Items
Then you just tell elements where to live using the grid-area property.
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.ads { grid-area: ads; }
.footer { grid-area: footer; }
Responsive Magic
This is where grid-template-areas truly shines. usage. To change the layout for mobile, you just query the areas, not the lines.
Desktop Layout
In the example above, we have a 3-column layout.
Mobile Layout
For mobile, we often want a single column. instead of complex math, we just redefine the string:
@media (max-width: 600px) {
.container {
grid-template-columns: 1fr; /* Single column */
grid-template-areas:
"header"
"main"
"sidebar"
"ads"
"footer";
}
}
Boom. Sidebar moved to the bottom. No math required.
Advanced: Empty Cells
Need whitespace? Use a dot (.). This is useful for creating offsets without margin hacking.
grid-template-areas:
"header header ."
"main main sidebar";
Common Pitfalls
- Rectangles Only: You cannot create L-shaped areas. All areas must be rectangles.
- Connected Areas: You cannot have
headerin the top left andheaderin the bottom right without connecting them. - Syntax: A single typo in the string invalidates the entire property.
Advertisement
Test Your Knowledge
Let's see if you understood the rules of Grid Areas.
Which of the following grid-template-areas definitions is INVALID?
Conclusion
grid-template-areas is underused because it looks "verbose". But for main page layouts, it is significantly more maintainable than line-based placement. It turns your CSS into self-documenting code.
Md Nasim Sheikh
Software Developer at softexForge