CSS
Holy Grail Layout with CSS Grid `grid-template-areas`
Implement the classic 'Holy Grail' website layout (header, nav, main, sidebar, footer) using semantic CSS Grid `grid-template-areas` for clear structure.
/* HTML Structure:
<div class="holy-grail-layout">
<header class="header">Header</header>
<nav class="navigation">Navigation</nav>
<main class="main-content">Main Content</main>
<aside class="sidebar">Sidebar</aside>
<footer class="footer">Footer</footer>
</div>
*/
.holy-grail-layout {
display: grid;
/* Define named areas for the layout */
grid-template-areas:
"header header header"
"nav main sidebar"
"footer footer footer";
/* Define row heights */
grid-template-rows: auto 1fr auto;
/* Define column widths */
grid-template-columns: 150px 1fr 200px;
min-height: 100vh; /* Make layout full viewport height */
gap: 10px; /* Space between grid cells */
background-color: #f9f9f9;
}
.header, .navigation, .main-content, .sidebar, .footer {
padding: 20px;
border: 1px solid #ddd;
text-align: center;
font-weight: bold;
}
.header { grid-area: header; background-color: #ffe0b2; }
.navigation { grid-area: nav; background-color: #c8e6c9; }
.main-content { grid-area: main; background-color: #bbdefb; }
.sidebar { grid-area: sidebar; background-color: #ffccbc; }
.footer { grid-area: footer; background-color: #e0e0e0; }
/* Responsive adjustments for smaller screens */
@media (max-width: 768px) {
.holy-grail-layout {
grid-template-areas:
"header"
"nav"
"main"
"sidebar"
"footer";
grid-template-rows: auto auto 1fr auto auto; /* Main content takes remaining space */
grid-template-columns: 1fr; /* Single column layout */
}
.navigation, .sidebar {
order: 0; /* Reset order if needed for mobile stack */
}
}
How it works: This snippet demonstrates the "Holy Grail" layout using CSS Grid's `grid-template-areas` property. This approach allows you to visually define the grid structure using named areas directly in your CSS, making complex layouts incredibly readable and maintainable. Each element (`header`, `nav`, `main`, `sidebar`, `footer`) is assigned a `grid-area` name, and the `grid-template-areas` property on the container then "draws" the layout. `grid-template-rows` and `grid-template-columns` define the sizes of the rows and columns, with `1fr` ensuring the main content fills available space. A media query is included to demonstrate how easily the layout can be transformed for mobile screens.