Sticky footers have been an issue most frontend developers have run into and everyone has their own way of dealing with them. In this post, I’m going to go over how I create sticky footers using jQuery.

Why jQuery?

Yes, this can be done using CSS as illustrated over at css-tricks.com. The benefit of this is not worrying about users who don’t have javascript enabled. What I dislike about using CSS is often you need to either adjust your HTML structure or know the exact height of your footer.

How it Works

An average site consists of 4 elements I’ll be targeting. The body, header, main content area and footer. What I want to do is dynamically set a min-height CSS style to the main content area. To work out what the min-height should be I simply minus the header & footer height from the body height.

Let’s assume you have a body height of 800px and a header & footer of 100px each. In theory, would mean the min-height of your main content area should be 800 – 100 – 100 = 600px.

The Code

We start by getting the height of the body, header & footer.

var body = jQuery(document).height();
var header = jQuery('#header').outerHeight();
var footer = jQuery('#footer').outerHeight();

Next, set the min-height variable by subtracting the header & footer from the body.

var minheight = body - header - footer;

Finally, we target the main content area and set the min-height.

jQuery('#main-content').css({'min-height':minheight});

Altogether this is the code. You’ll need to adjust the target elements to match your HTML.

jQuery(document).ready(function() {

	var body = jQuery(document).height();
	var header = jQuery('#header').outerHeight();
	var footer = jQuery('#footer').outerHeight();

	var minheight = body - header - footer;

	jQuery('#main-content').css({'min-height':minheight});

});

Hope this was helpful or if you know of a better way of creating a sticky footer.