Digital Bliss

Sticky Footer

using flex

Having the footer on a webpage stick to the bottom of the page if the content is not big enough is a very common problem in website development. Up until now the solution involved a fixed and known footer height like this or this.

More recently with support for flex increasing it has, depending on your browser support requirements, become more straightforward to use flex for the solution.

For this website we used this solution for the first time.

It is a very straightforward and clean solution:

body {
.main-content {

Where .main-content is the element that is on the same level as the footer and contains the main content:

<div class=“main-content”>The main content container</div>
<footer>The footer</footer>

Yes but how exactly does this work?

First of all the display property of the body is set to flex, this makes the body element use the flexbox layout.

Next we set the min-height property to 100vh. vh is a length unit in css that represents 1/100th of the viewport height (vh) with decent browser support, so practically we making sure that the body takes up the entire height of the window.

With flex-direction: column we are setting the way the elements are laid out inside the flexbox layout, column lays the elements in a column with the first one on the top and the others following.

Finally we set flex-grow: 1 for the .main-content, flex-grow determines the element’s ability to grow within its container. There are no units for this property, it is only a value that determines the proportion of space the element will take. Since the value defaults to 0 the footer will have a value of 0 and the main content container a value of 1 which means it will stretch to take up all empty space.