CSS
Design Complex Layouts with CSS Grid Template Areas
Master `grid-template-areas` to create semantically clear and easily maintainable complex page layouts with CSS Grid, improving responsiveness.
.grid-container {
display: grid;
grid-template-columns: 1fr 3fr 1fr; /* Example: Sidebar, Main, Another Sidebar */
grid-template-rows: auto 1fr auto; /* Header, Content, Footer */
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
gap: 1rem;
min-height: 100vh;
font-family: sans-serif;
box-sizing: border-box;
}
.header { grid-area: header; background-color: #f2f2f2; padding: 1rem; text-align: center; }
.nav { grid-area: nav; background-color: #e0e0e0; padding: 1rem; }
.main { grid-area: main; background-color: #ffffff; padding: 1rem; }
.aside { grid-area: aside; background-color: #e0e0e0; padding: 1rem; }
.footer { grid-area: footer; background-color: #f2f2f2; padding: 1rem; text-align: center; }
@media (max-width: 768px) {
.grid-container {
grid-template-columns: 1fr;
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
}
}
/* Basic HTML structure for context */
/*
<div class="grid-container">
<header class="header">Header</header>
<nav class="nav">Navigation</nav>
<main class="main">Main Content</main>
<aside class="aside">Sidebar</aside>
<footer class="footer">Footer</footer>
</div>
*/
How it works: This snippet illustrates how to build complex and responsive page layouts using CSS Grid's `grid-template-areas` property. You define a named grid area for each major section (e.g., `header`, `nav`, `main`), then assign these names to a visual grid structure. This approach makes the layout highly readable and easy to modify, especially with media queries, allowing you to reconfigure the entire layout with a few lines of code without touching the HTML structure.