April 12, 2010

Sticky Footer at Bottom of Page using JQuery

I was developing a site for my client and I decided that I wanted to make my footer stick to the bottom of the page regardless of the amount of content. I did a search for “sticky footers” and found some good CSS hacks. The problem is that it’s a little hard to implement once you have a majority of you site structured a specific ways.

I can tell you now that the CSS hacks for a sticky footer doesn’t cooperate well when you have margins declared in other div classes. I spent about an hour trying to get my footer to work right. It would work well in some pages but in others, would display a vertical scroll bar with 20 pixels or so left to scroll.

I got fed up and decided to try and use JQuery to solve my problems. It worked brilliantly! And it’s as simple as this. If my window height is greater than my content plus footer height, add the appropriate top padding to the footer that will keep it always on the bottom. If the content height is greater than the windows height, leave the padding as it was previously declared in your css. And just make sure you calculate the top padding on page load and when the window is resized.

Sticky Footer

Here is the code. Just put it at the end of your page somewhere. Make sure you change the class name ‘.footer’ with whatever class or id name you are using for your footer.

$(function(){
	positionFooter(); 
	function positionFooter(){
		var padding_top = $(".footer").css("padding-top").replace("px", "");
		var page_height = $(document.body).height() - padding_top;
		var window_height = $(window).height();
		var difference = window_height - page_height;
		if (difference < 0) 
			difference = 0;
 
		$(".footer").css({
			padding: difference + "px 0 0 0"
		})
	}
 
	$(window)
		.resize(positionFooter)
});
  1. Thank you very much! Modified it to expand the div above the footer to add bottom-padding instead, and works perfectly. Thanks!

    Comment by Peter — May 3, 2010 @ 2:59 am

  2. Just stumbled across this – brilliant! Many thanks. How would you tweak it to work as Peter says previously – ie with the padding at the bottom rather than the top? I’ve been monkeying around with the script but I don’t know what I’m doing. Thanks, Mike.

    Comment by Michael — May 25, 2010 @ 10:02 am

Leave a comment