January 8, 2011

Sticky Footers

Sometimes, in websites that you design, you'll find that you want to implement some kind of footer (with copyright information, contact links, etc). The naive way to go about adding a footer to your design to just add a div with some fixed (or auto) height at the bottom, like so:

<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>

This should work, right? Well, this works as expected in certain cases when your content is longer than the height of your browser (figure on the left). In the case where you have very little (or no) content on one of your pages, the footer "slides up", leaving an awkward looking space below your footer (figure on the right).

To force the footer to stick to the bottom, thus the name "sticky footers", you need to wrap all other content in a container div, and give this div a height of 100% and negative bottom margin of whatever the height of the footer is.

This way, the footer is always forced to the bottom in cases where the content isn't long enough, and still works as before when the content is long enough. You'll notice that the negative margin causes the lower portions of your content to overlap with the footer; this can be fixed with some simple bottom padding or a div fixed to the height of the footer.

<div id="container">
  <div id="header"></div>
  <div id="content"></div>
  <div id="push"></div>
</div>
<div id="footer"></div>

And the css:

html, body { height: 100%; margin: 0; }
#container {
  min-height: 100%;
  height: auto !important;
  height: 100%;
  margin: 0 auto [footer-height];
}
#footer, #push {
  height: [footer-height];
}

And that's it! Simple, really!

Credits: I first learned how to do this from Ryan Fait.