sajad torkamani

A sticky footer is a footer that must always appear right at the bottom of the screen even if there is little content on the page. Thanks to Flexbox, you can implement a sticky footer without resorting to strange CSS or even JavaScript hacks.

The approach is something like this:

  • Wrap all our HTML elements within a wrapper element.
  • Make the wrapper element a flex container and set its flex-direction to column so that its child elements are stacked vertically.
  • Utilize Flexbox’s layout model to make the footer stick to the bottom of the screen.

So, assuming a basic HTML document structure where you use <body> as a wrapper element:

<body>
  <header class="site-header">...</header>
  <div class="site-content">...</div>
  <footer class="site-footer">...</footer>
</body>

You can make the .site-footer element sticky by applying the following CSS:

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

.site-content {
  flex: 1;
}

This works because you’re setting flex: 1 on .site-content which makes it expand to fill all the available space on the screen.

For example, if your browser screen had a height of 1000px and .site-header was 200px and .site-footer was 100px, then .site-content would fill up all the remaining 700px, thus pushing .site-footer right to the bottom of the screen.

The beauty of this approach is that you don’t have to know the height of the footer or any other element. It will work regardless.

Here’s a CodeSandbox demonstrating this technique.

Tagged: CSS