CSS
Design Complex Page Layouts with CSS Grid Template Areas
Master CSS Grid's `grid-template-areas` to create sophisticated, readable, and maintainable page layouts like the Holy Grail layout with ease.
/* HTML Structure Example: */
/*
<div class="grid-page-layout">
<header class="grid-header">Header</header>
<nav class="grid-nav">Navigation</nav>
<main class="grid-main">Main Content</main>
<aside class="grid-aside">Sidebar</aside>
<footer class="grid-footer">Footer</footer>
</div>
*/
.grid-page-layout {
display: grid;
/* Define named grid areas and their layout */
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
grid-template-columns: 200px 1fr 200px; /* nav fixed, main grows, aside fixed */
grid-template-rows: auto 1fr auto; /* Header/footer auto, main grows */
gap: 1rem;
min-height: 100vh;
font-family: sans-serif;
color: #333;
}
/* Assign elements to their named grid areas */
.grid-header { grid-area: header; background-color: #f0f0f0; padding: 1rem; text-align: center; }
.grid-nav { grid-area: nav; background-color: #e0e0e0; padding: 1rem; }
.grid-main { grid-area: main; background-color: #ffffff; padding: 1rem; }
.grid-aside { grid-area: aside; background-color: #e0e0e0; padding: 1rem; }
.grid-footer { grid-area: footer; background-color: #f0f0f0; padding: 1rem; text-align: center; }
/* Basic responsive adjustment for smaller screens */
@media (max-width: 768px) {
.grid-page-layout {
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
grid-template-columns: 1fr;
grid-template-rows: auto auto 1fr auto auto; /* Main content still grows */
}
}
How it works: This snippet showcases the power of CSS Grid's `grid-template-areas` for creating complex yet highly readable page layouts, often referred to as a 'Holy Grail' layout. By defining named areas in a visual manner (`header`, `nav`, `main`, `aside`, `footer`), developers can intuitively structure their page. `grid-template-columns` and `grid-template-rows` then define the sizes of these tracks. The example also includes a basic media query to demonstrate how easily the layout can be reconfigured for smaller screens by simply redefining the `grid-template-areas` and track sizes.