Keeping the footer at the bottom with CSS Flexbox

Dominik Weber - Feb 4 '18 - - Dev Community

Just now I've read the post Keeping the Footer at the Bottom with CSS-Grid.
While reading, I somehow got the impression that doing the same with 'just' flexbox is difficult. It's not.

This is not to belittle the referenced post in any way, it is very well explained, and in my opinion more elegant than with flexbox. I just want to explain that it is as easy with flexbox as it is with grid, so that if, for whatever reason, you cannot use grid, you don't shy away from implementing it with flexbox.

I'll use the same HTML as in the referenced article:

<html>
    <body>
        <article>
            <header>
            </header>
            <main>
            </main>
            <footer>
            </footer>
        </article>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And here the CSS to put the footer at the bottom, where it belongs:

html, body {
    width: 100%;
    height: 100%;
}

article {
    min-height: 100%;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

main {
    flex-grow: 1;
}

header, main, footer {
    flex-shrink: 0;
}

Enter fullscreen mode Exit fullscreen mode

On the container, we set flexbox to align the contents in a column. The elements should stretch so that they span the whole width, and not just the width their contents take up.

Setting flex-grow: 1 on main makes it grow to fill the available space. This puts the footer at the bottom, since main takes up all the space in the middle.

The use for flex-shrink: 0 is probably less obvious, and it is often forgotten. At least I forgot it way more often than I'd like to admit.

By default, flex-shrink is set to 1. This makes the items shrink if there is not enough space, which happens if the content is larger than the screen. The results can look very weird, e.g. a button that is smaller than the text it contains. Setting it to 0 stops that behavior.

That's it. That's everything you need to know to position the footer at the bottom with flexbox. :)


Follow me on Twitter for more of my thoughts, articles, projects and work.

. . . . . . . . . . . . . .
Terabox Video Player