CSS
Build a Complex Page Layout with CSS Grid Template Areas
Design a multi-section web page, including header, navigation, main content, sidebar, and footer, using CSS Grid's intuitive `grid-template-areas` for clear structure.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid Template Areas Layout</title>
<style>
body {
display: grid;
grid-template-columns: 1fr 3fr 1fr; /* Nav | Main | Aside */
grid-template-rows: auto 1fr auto; /* Header | Content | Footer */
grid-template-areas:
"header header header"
"nav main aside"
"footer footer footer";
min-height: 100vh; /* Ensure the grid takes full viewport height */
margin: 0;
gap: 10px; /* Space between grid items */
font-family: sans-serif;
}
header {
grid-area: header;
background-color: #a0d2eb;
padding: 20px;
text-align: center;
}
nav {
grid-area: nav;
background-color: #e0f2f7;
padding: 20px;
}
main {
grid-area: main;
background-color: #f7fafc;
padding: 20px;
}
aside {
grid-area: aside;
background-color: #e0f2f7;
padding: 20px;
}
footer {
grid-area: footer;
background-color: #6a82fb;
color: white;
padding: 20px;
text-align: center;
}
/* Basic styling for demonstration */
div { border-radius: 5px; }
h1, h2 { margin-top: 0; }
@media (max-width: 768px) {
body {
grid-template-columns: 1fr; /* Single column layout */
grid-template-rows: auto auto 1fr auto auto; /* Header | Nav | Main | Aside | Footer */
grid-template-areas:
"header"
"nav"
"main"
"aside"
"footer";
}
}
</style>
</head>
<body>
<header>
<h1>Website Header</h1>
</header>
<nav>
<h2>Navigation</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
<main>
<h2>Main Content</h2>
<p>This is the primary content area of the webpage. It adapts its position based on the grid structure defined.</p>
</main>
<aside>
<h2>Sidebar</h2>
<p>Additional information or widgets go here.</p>
</aside>
<footer>
<p>© 2023 Grid Layout Example</p>
</footer>
</body>
</html>
How it works: This snippet demonstrates creating a full-page layout using CSS Grid's `grid-template-areas`. Named grid areas (e.g., `header`, `nav`, `main`, `aside`, `footer`) are defined and then placed visually in the `grid-template-areas` property, providing a highly readable and maintainable layout structure. A media query is included to demonstrate how to easily adapt the layout to a single column on smaller screens, showcasing Grid's responsiveness.