Contents
Introduction
A common problem for many developers. Let's say you create a website that looks perfect in every browser until you find a page without much content on it.
CSS Approach
As previously mentioned, being a common problem, searching on Google should provide you with decent results that mostly suggest the followings:
- In the first place create a <div> that must be directly inside the <body> and which should serve as a container for all the page content like in the example below:
<body> <div id="container"> <div id="header"></div> <div id="content"></div> <div id="footer"></div> </div> </body>
- Secondly apply CSS rules to the following elements:
html, body { height: 100%; } #container { min-height: 100%; position: relative; } #content { padding-bottom: 100px; /* Height of the footer element */ } #footer { width: 100%; height: 100px; /* Same height specified above */ position: absolute; bottom: 0; }
The content <div> has a bottom padding equal to the height of the footer stretching the container <div> which is set to position:relative that force the footer <div> all the way to the bottom taking up that extra padding space.
jQuery Approach
Usually in most situations the css approach should keep the footer at the bottom of the page but from experience I've learn that WordPress for example isn't that friendly with the method. That's why instead of css I suggest the followings:
In this scenario, the website sends Ajax requests based on the user filtering on different categories so the content it has different heights every time. Unfortunately this combined with the CMS framework that supports it makes jQuery the right solution.
- First create a new css class called for example "stayDown" with the following rule:
.stayDown { position: fixed; bottom: 0; width: 100%; }
- Then every time the user filter so the ajax function is executed add the above class to the footer:
jQuery("footer").addClass("stayDown");
This should be placed at the beginning of the function.
- On the ajax method after the response is used as the html content of the selected <div> add the following piece of code:
jQuery("footer").removeClass("stayDown"); var y = jQuery(window).height(); var x = jQuery('.main-header').height() + jQuery('.wrap').height() + jQuery('#wpadminbar').height(); var z = y-x; if (z >= 98) { jQuery("footer").addClass("stayDown"); }
It must be placed after the new html content is rendered inside the selected <div> because of the changes in height that can occur. Firstly it removes the class "stayDown" from the footer. In the "y" variable is stored the current browser window height and in the "x" variable is stored the height of all content excepting the footer. After that knowing the previous mentioned variables we can calculate the remaining empty space for our footer and store it in the "z" variable. If exceeds 98 which is the footer height value in pixels the "stayDown" class is added otherwise nothing happen.