How can I ensure the footer is always at the bottom of the page?

CSS, Layout · Oct 30, 2022

Preventing the footer from floating up the page is important when trying to create a polished website. Pages with short content can run into this issue, but it's easy to fix with a few lines of CSS. Assuming your HTML looks something like the snippet below, here are two modern ways to ensure the footer is always at the bottom of the page:

  <main><!-- Main content --></main>
  <footer><!-- Footer content --></footer>

You can use flexbox to ensure that the footer is always at the bottom of the page. This is done by setting the giving the body element min-height: 100vh, display: flex and flex-direction: column. Then, give the footer element a margin-top: auto to make its margin fill the remaining space between it and its previous sibling. Note that this technique will not stretch the previous sibling, but rather push the footer to the bottom of the page.

body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;

footer {
  margin-top: auto;

You can also use grid in a very similar fashion. Simply swap display: flex for display: grid and flex-direction: column for grid-template-rows: 1fr auto in the body element. No additional attributes are needed for the footer element. In this case, the fr unit is leveraged to stretch the main element to fill the remaining space.

body {
  min-height: 100vh;
  display: grid;
  grid-template-rows: 1fr auto;

As you can see, both techniques are straightforward to implement. Depending on your needs one might be more suitable than the other. Generally speaking, grid is more flexible in most cases and can help if you have more complex layouts, which can include a header or sidebar.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • 4 ways to center content with CSS

    Centering content with CSS might often feel tricky. Here are 4 easy tricks you can use in your code today.

    CSS, Layout · Sep 28, 2021

  • Menu on image hover

    Displays a menu overlay when the user hovers over the image.

    CSS, Layout · Oct 11, 2021

  • Offscreen

    Hides an element completely (visually and positionally) in the DOM while still allowing it to be accessible.

    CSS, Layout · Oct 11, 2021