CSS
Sticky Header & Footer in a Full-Height Grid Layout
Build a full-height web layout using CSS Grid where a header and footer remain sticky at the top and bottom, respectively, while the main content area scrolls independently.
html, body {
height: 100%;
margin: 0;
}
.grid-page-layout {
display: grid;
grid-template-rows: auto 1fr auto; /* Header, Content (takes remaining space), Footer */
height: 100vh; /* Make the grid take the full viewport height */
font-family: sans-serif;
border: 1px solid #ccc;
}
.grid-header {
background-color: #333;
color: white;
padding: 15px;
text-align: center;
}
.grid-main-content {
background-color: #f4f4f4;
padding: 20px;
overflow-y: auto; /* Make the content area scrollable */
max-height: 100%; /* Important for overflow to work correctly within the 1fr row */
}
.grid-footer {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
}
/* HTML Structure */
<!--
<div class="grid-page-layout">
<header class="grid-header">Website Header</header>
<main class="grid-main-content">
<h1>Main Content Area</h1>
<p>This is the main content area. It will scroll if its content is too long to fit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>...</p> <!-- Add more content here to test scrolling -->
<p>...</p>
<p>...</p>
<p>...</p>
<p>End of content.</p>
</main>
<footer class="grid-footer">Website Footer</footer>
</div>
-->
How it works: This snippet creates a common web page layout with a sticky header and footer using CSS Grid. The parent container (`.grid-page-layout`) is set to `display: grid` and given a `height: 100vh` to span the full viewport height. The `grid-template-rows: auto 1fr auto;` declaration is key: the `auto` values ensure the header and footer rows only take up as much height as their content requires, while `1fr` tells the main content row to fill all remaining vertical space. By applying `overflow-y: auto` to the `.grid-main-content` area, its content becomes independently scrollable without affecting the position of the header or footer, creating a professional and functional application layout.