Sticky footer at the bottom of the page in CSS
4 A footer that stays at the bottom
fairKeep a footer at the bottom of the viewport when the page is short, but let it sit below the content when the page is long.
Stuck? Three hints, smallest first
- 1. Make the page a column flex container at least as tall as the viewport.
- 2. Give the main content
flex: 1so it absorbs the leftover space. - 3.
min-height: 100vh, notheight: with a fixed height, long content would overflow instead of pushing the footer down.
<div class="page">
<header>Header</header>
<main>Short content</main>
<footer>Always at the bottom</footer>
</div>
.page {
display: flex;
flex-direction: column;
min-height: 260px; /* stands in for 100vh so the preview shows the effect */
}
.page main {
flex: 1; /* soak up whatever space is left over */
padding: 12px 0;
}
.page header,
.page footer {
padding: 10px;
background: #f2f3f5;
border-radius: 6px;
}
6 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('the page is a flex column', declares(css, 'flex-direction', 'column'), true);
test('it is a flex container', declares(css, 'display', 'flex'), true);
test('the main area absorbs the spare space', declares(css, 'flex', '1'), true);
test('a minimum height, not a fixed one', /min-height\s*:/.test(css), true);
test('height is not fixed, which would clip long content', /[^-]height\s*:\s*260px/.test(css), false);
test('semantic landmarks are used', ['header', 'main', 'footer'].every((t) => hasTag(html, t)), true);
Output
min-height rather than height is the whole distinction, and the fifth assertion pins it down. With a fixed height, content taller than the box overflows and the footer stays put at the wrong place; with a minimum, the container grows and the footer travels down with it. In a real page use 100vh — or better 100dvh, which accounts for mobile browser toolbars appearing and disappearing.