Full answer
On a short page the content does not fill the window, so the footer sits in the middle of the screen with empty space under it. The footer should be at the bottom of the window on short pages and after the content on long pages. position: fixed on the footer is wrong, because then it would cover content on long pages.
The modern fix makes the body a column that is at least as tall as the window and lets the main part take the free space.
With flexbox:
body { min-height: 100vh; display: flex; flex-direction: column; }
main { flex: 1; }With grid:
body { min-height: 100vh; display: grid; grid-template-rows: auto 1fr auto; }The header and footer take their own height, and 1fr gives all the rest to main.
Use min-height and not height, so the page can still grow when there is a lot of content. On phones, 100vh can be taller than the visible area when the address bar is shown. The newer dvh unit follows the visible height. Provide 100vh first as a fallback and 100dvh after it, because a browser that does not know dvh ignores that line. Also remove the default 8px body margin, or the page will be a little too tall and scroll.
With only a line of content, the footer's bottom edge is at the bottom edge of the window, and main fills the gap. If more content is added to main, the footer is pushed down and the page scrolls, with nothing overlapping.
Check the layout on a short page, on a very long page, and on a phone.
<style>
html, body { margin: 0; }
body {
min-height: 100vh;
min-height: 100dvh;
display: grid;
grid-template-rows: auto 1fr auto;
font-family: sans-serif;
}
header { background: #cde; padding: 8px; }
main { padding: 8px; }
footer { background: #333; color: #fff; padding: 8px; }
</style>
<header id="h">Header</header>
<main id="m">Short content</main>
<footer id="f">Footer</footer>Run in Chrome 156 (headless) as a page; the snippet is wrapped in a minimal HTML document with doctype, charset and viewport meta tag. Two full runs gave identical results, and the measured values in the answer come from them.
Key points
- Body needs min-height equal to the window height.
- Flex column with main flex: 1 or grid rows auto 1fr auto both work.
- Use min-height, so long content can still grow the page.
- Write 100vh first and 100dvh after it.
- Reset the default body margin.
Common mistakes
- Using position: fixed or absolute for the footer, which overlaps content on long pages.
- Using height: 100vh on the body, which makes the layout break when content is taller.
- Forgetting the default body margin, which creates a small unwanted scroll.
Follow-ups
- Why is min-height used instead of height?
- What does the 1fr row do in the grid version?
Tips
- Say min-height, not height, and give the reason.
- Mention the 100vh then 100dvh fallback pair.