Code for Heaven

Go to the home page

Sticky footer using CSS Flexbox

This is what happened today. I was given a report from Google Search Console, that one of the content pages of our customers fails mobile validation due to its content being wider than viewport width. After short inspection, I found guilty element, which was... <table>.

Since we already use bootstrap in our CSS code base, I wanted to solve this by using their responsive table solution. But it didn't work, no matter how hard I tried. After testing the table in excluded environment, I realized problem lays somewhere else among element's parents, or grand-grand-... parents. That's how I found that we had something called sticky footer in our styles.

For those of you interested in this old solution, you can follow this link to read more on it. For those of you, who wants to read about modern approach, please, continue reading.

Let me show my code first:

      body {
        display: flex;
        flex-direction: column;

        min-height: 100vh;
      main {
        flex-grow: 1;
      footer {
        flex-shrink: 0;
        This contents spans across whole viewport height.
        Footer! Always at the foor of your browser's window.

If you need legacy vendors' prefixes use Autoprefixer

Body is now a flexible container with vertical (flex-direction: column;) flow. I gave it min-height: 100vh (minimum height of 100% viewport height), so it'll always be at least this high, but if its content is higher, it will naturally expand vertically. I should not use justify-content: space-between, because I want main to remain right beneath header.

And it works in IE11.


Enjoyed it? Great! Let's stay in touch.