CSS
Build a Responsive Full-Page Layout with CSS Grid
Create a robust and responsive full-page layout including header, navigation, main content, and footer using CSS Grid's powerful template areas and media queries.
body {
margin: 0;
font-family: sans-serif;
}
.grid-container {
display: grid;
grid-template-rows: auto 1fr auto; /* Header, Main content (grows), Footer */
grid-template-columns: 1fr; /* Single column by default */
grid-template-areas:
"header"
"main"
"footer";
min-height: 100vh; /* Ensures layout takes full viewport height */
}
header {
grid-area: header;
background-color: #333;
color: white;
padding: 1em;
text-align: center;
}
main {
grid-area: main;
padding: 1em;
background-color: #f4f4f4;
}
footer {
grid-area: footer;
background-color: #333;
color: white;
padding: 1em;
text-align: center;
}
/* Responsive layout for larger screens */
@media (min-width: 768px) {
.grid-container {
grid-template-columns: 200px 1fr; /* Sidebar, Main content */
grid-template-areas:
"header header"
"nav main"
"footer footer";
}
nav {
grid-area: nav;
background-color: #555;
color: white;
padding: 1em;
}
/* Include a nav element in HTML for this media query */
}
/* HTML Structure */
/*
<div class="grid-container">
<header>Header</header>
<nav>Navigation</nav> (Optional, uncomment for larger screens)
<main>Main Content</main>
<footer>Footer</footer>
</div>
*/
How it works: This snippet demonstrates a flexible full-page layout using CSS Grid. `grid-template-areas` defines named regions, making the structure intuitive. `grid-template-rows: auto 1fr auto` ensures the header and footer take minimal space while the main content (`1fr`) fills the remaining vertical space. A media query dynamically changes the layout to include a sidebar on larger screens, showcasing responsiveness.