Using CSS flex to create a sticky footer

Flex

Flex is a new way to solve many layout problems in CSS. Chris has written an excellent guide to using flex on css-tricks.com, be sure to check that out.

As with most nice CSS features, they are not supported in older versions of Internet Explorer. Other modern browsers have had support for flex for a long time.

One of the common problems that flex can solve is making a footer stick to the bottom of the page when there is little content on the page and keeping it below the content when there's a lot of it. This is surprisingly easy. Have a look at the source of this page and the CSS stylesheet.

The sticky footer

Creating a basic page with a sticky footer using flex requires three things:

  • A container element with the following style properties set:
    display: flex;
    flex-direction: column;
    height: 100%;
  • A child of the container element that will contain the page content with:
    flex: 1 0 auto;
  • The footer (and any other elements that should not resize like the header), also as a child of the container element with:
    flex: 0 0 auto;

display: flex; enables the flex functionality for the container element, flex-direction: column; makes sure that the children of the flex-container are laid out vertically instead of horizontally (which is the default). height: 100%; ensures that the container takes up all the space in the parent element. In the case of a full page that means you also need to set the height of html and body element to 100% or the container will not fill the entire page.

flex: 1 0 auto; on the content container will allow that container to grow when space is left over but will not allow it to shrink. flex: 0 0 auto; on the footer and other elements makes sure that those elements do not get resized.

See how the footer reacts with more content on the page. And with less content.