sajad torkamani

Creating a footer that sticks to the bottom of the page is a task that many developers encounter at some point. What makes the “sticky footer” challenging is that the footer must appear right at the bottom of the screen even if there is very little content on the page.

Thanks to Flexbox, we no longer need to resort to strange CSS or even JavaScript hacks.

The approach is something like this:

So, assuming a basic HTML document structure where we use <body> as our wrapper element.

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

We 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 we are setting flex: 1 on .site-content which makes it expand to fill all the available space on the screen.

For example, if our 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 we don’t have to know the height of the footer or any other element. It just works!

Here’s a CodeSandbox demonstrating this technique.