CSS
Build a Full-Height Page Layout (Header, Main, Footer) with CSS Grid
Design a complete page layout that spans the full viewport height using CSS Grid. This snippet shows how to structure a page with distinct header, main content, and footer areas, adapting to different content lengths.
html, body {
height: 100%;
margin: 0;
}
.grid-container {
display: grid;
grid-template-rows: auto 1fr auto; /* Header, Main (grows), Footer */
height: 100%;
}
.header {
background-color: #f8f8f8;
padding: 20px;
text-align: center;
}
.main {
background-color: #ffffff;
padding: 20px;
overflow-y: auto; /* Allows content to scroll if it overflows */
}
.footer {
background-color: #333;
color: white;
padding: 15px;
text-align: center;
}
/* HTML Context */
/*
<div class="grid-container">
<header class="header"><h1>Website Header</h1></header>
<main class="main">
<p>This is the main content area. It will fill the available space between the header and footer.</p>
</main>
<footer class="footer">Copyright © 2023</footer>
</div>
*/
How it works: The `html` and `body` are set to `height: 100%`. The `.grid-container` is then set to `display: grid` and `height: 100%`. `grid-template-rows: auto 1fr auto` defines three rows: the header takes its intrinsic height (`auto`), the main content row takes all remaining available space (`1fr`), and the footer takes its intrinsic height (`auto`). `overflow-y: auto` ensures the main content scrolls independently if it exceeds its allocated space.