How to make a footer with minimal CSS

Our goal is to make a footer that stay at the bottom of the page, even if the screen is not filled with content.

The basis of putting the footer-element in the bottom of the document is the following CSS snippet.

footer {
	position: absolute;
	bottom: 0px;
}

Unfortunately, when the document is smaller than the window, the footer just floats awkwardly in the middle of the window. We don't want that. To fix this problem we tell the html-element to be at least as tall as its parent, i.e. the window.

html {
	min-height: 100%;
}

Now when the content doesn't exceed the page, the footer is at the bottom as it's supposed to be. But when the content grows beyond the window, the footer doesn't move below the content, but rather sits on top of it. This problem occurs because the footer doesn't position itself according to the document size, but according to the window size. The following snippet fixes this, as a relative position is always relative to the nearest absolutely positioned ancestor; previously the window, now the html-element

html {
	position: relative;
}

Now the footer behaves as we want it to, but there's still a tiny problem; the footer overlaps content, when the window is too small. To fix this, we need to allow extra space for the footer, by adding some padding to the bottom of the html-element. This unfortunately requires that the footer has a constant height, or at least a max-height.

html {
	padding-bottom: 20px;
}

However, this approach introduces a new problem: The footer is just below the windows edge, when loading the page, and there will always be a scrollbar. This is undesirable when the content doesn't fill the page, so we have to fix it. Luckily CSS3 introduced box-sizing. By setting this to border-box, the height of the element it's applied to includes the padding and border on the inside, instead of the default situation, where padding is added after the height is calculated.

html {
	box-sizing: border-box;
	-moz-box-sizing: border-box;
}

This automagically eradicates the problems with height: 100%; and non-zero padding on the same element, and allows us to easily have a footer permanently at the bottom of the page.

Resulting CSS

footer {
	position: absolute;
	bottom: 0px;
	height: 20px
}

html {
	min-height: 100%;
	position: relative;
	padding-bottom: 20px;
	box-sizing: border-box;
	-moz-box-sizing: border-box;
}

This trick depends on a few assumptions:

  1. The height of the footer is constant and not larger than the padding at the bottom of html
  2. There is only a single footer-element. If more are needed, simply select the correct with an id.

And here's an example of the code in use.