Getting the footer of a website to always stick to the bottom of the page, regardless of the content’s length, used to be a hassle.

With Flexbox, making a sticky footer is easy, and requires only a few lines of code.

For those of you unfamiliar with flexbox, it is the newest and most modern way to create layouts in CSS, and is well supported in all modern browsers.

Now, let’s take a look at the code necessary to create a sticky footer.

HTML:

<body>
  <header></header>
  <main></main>
  <footer></footer>
</body>

CSS:

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

main {
  flex-grow: 1;
}

Step-by-step explanation

  1. First, we make our <body> element a flex container and set the direction of the flex children to column, so that the sections of our site will stack on top of each other.

  2. Next, we make the <body> element stretch all the way to the bottom of the page, by setting it’s viewport height (vh) to 100% of the browser window. This leaves extra space, which a flex item can take up.

  3. Lastly, we tell our <main> element to grow and take up the available space. Since the default value of flex-grow is 0, the header and footer will not grow, but the <main> element will take up all the remaining space.

And there you go! A clean and easy way of making a sticky footer with flexbox.