CSS
Complex Grid Layouts with Named Areas
Master CSS Grid's named areas to build intuitive and maintainable complex layouts, assigning specific regions for content placement with semantic names.
<style>
.layout-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* left-sidebar main right-sidebar */
grid-template-rows: auto 1fr auto; /* header content footer */
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
gap: 15px;
min-height: 100vh;
background-color: #f5f5f5;
padding: 15px;
}
.header { grid-area: header; background-color: #007bff; color: white; padding: 1rem; text-align: center; }
.nav { grid-area: nav; background-color: #e9ecef; padding: 1rem; }
.main { grid-area: main; background-color: #ffffff; padding: 1rem; }
.aside { grid-area: aside; background-color: #e9ecef; padding: 1rem; }
.footer { grid-area: footer; background-color: #343a40; color: white; padding: 1rem; text-align: center; }
/* Responsive adjustment for smaller screens */
@media (max-width: 768px) {
.layout-container {
grid-template-columns: 1fr;
grid-template-rows: auto auto 1fr auto auto; /* Header, Nav, Main, Aside, Footer */
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
}
}
</style>
<div class="layout-container">
<header class="header">Site Header</header>
<nav class="nav">Navigation</nav>
<main class="main">Main Content Area</main>
<aside class="aside">Side Advertisements</aside>
<footer class="footer">Site Footer</footer>
</div>
How it works: This snippet showcases the power of CSS Grid's `grid-template-areas` for creating complex yet readable layouts. By defining named areas like 'header', 'nav', 'main', 'aside', and 'footer' in a visual ASCII-art like structure, developers can easily map content to specific regions of the grid. `grid-template-columns` and `grid-template-rows` define the size of these implicitly created tracks. Each child element then uses `grid-area` to specify which named area it occupies, making the layout structure highly semantic and easy to modify, especially with responsive adjustments using media queries.