Make a Simple Sticky Footer with 4 Lines of Flexbox Code: Learn CSS

One of web layout’s long-standing problems has been how to make footers stay put. If there’s not enough content on a page to push it down, a footer can creep up and leave a blank canvas underneath. Flexbox CSS can solve this problem almost instantly.

Let’s say we have a very simple website with nav, main, and footer elements wrapped inside our body. Flexbox works by applying its flex status to the first level of children inside a parent: body is the parent.

body {
  display: flex;
}

Flexbox’s default is to arrange children in a row, but we want them in a vertical column, so we need another line of code.

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

Nothing’s happened to our footer yet. The flex children will flex to fill the available space of its parent, which means we need to give the body a height to fill.

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

The vh unit is a percent measure of the height of the viewport window. Our site probably has more than one screen of content, so we’ll use min-height instead of height to set a minimum.

Our footer still isn’t in the right place. We’ll do that by telling main to take up the extra space on the page instead of leaving it for after our HTML finishes. Let’s give it our flex instructions.

main {
  flex-grow: 1;
}

This could also be written with the flex shorthand property, which incorporates flex-grow, flex-shrink, and flex-basis. That would look like this:

main {
  flex: 1 0 auto;
}

Fallbacks and Older Browsers

Flexbox won’t cause any problems in older browsers, it just won’t work and the footer will unstick. But vh units aren’t supported by Internet Explorer 8 or earlier browsers. If you’d like to make sure this technique won’t break your site on IE, we need to add fallback heights.

html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100%;
  height: 100vh;
}

The percent unit measures its parent’s size, not the screen like vh and vw. So we need to set a new height on the HTML root for the body to use.

You’re thinking the body height should be a min-height. But as Chris Coyier noted on CSS Tricks in 2009: “IE treats ‘height’ how ‘min-height’ is supposed to be treated.”

Finally: Don’t forget to use prefixes on all the Flexbox stuff for browser compatibility.

Sticking It All Together

html {
  height: 100%; /* IE8 fallback */
}

body {
  display: flex;
  flex-direction: column;
  min-height: 100%; /* IE8 fallback */
  min-height: 100vh;
}

main {
  flex-grow: 1;
  /* or use the shorthand: */
  flex: 1 0 auto;
}

Test this code yourself on Codepen.

See the Pen Flexbox Sticky Footer with IE8 fallback by David Greenwald (@davidegreenwald) on CodePen.

Reference:
Solved by Flexbox: Sticky Footer