CSS: sticky footer

A footer always at the bottom of a page is one of the most requested features of web development with CSS. CSS can accomplish this task quite easily. It's only required a basic knowledge of positioning and box model, particularly what is related to the calculations of minimum and maximum heights. These calculations will be applied to the html and body elements because these elements represent the whole viewport of a web browser in HTML. Let's see a basic HTML structure to start with:

<body>
<div id="content">
  <!--main content here-->
</div>
<div id="footer">...</div>
</body>

The first thing we have to do is to set the height and minimum height of the viewport to 100%:

html, body {
 margin: 0;
 padding: 0;
 height: 100%;
 min-height: 100%;
}

We've also removed padding and margins. Now let's set a contextual positioning for our footer:

body {
 position: relative;
}

Since the main content is not aware of the presence of the footer, we need to add an extra bottom padding to take care of that:

#content {
 padding-bottom: 5em;
}

Finally, the footer itself:

#footer {
 width: 100%;
 height: 2em;
 line-height: 2;
 font-size: 1.5em;
 text-align: center;
 background: #d40;
 color: #fff;
 position: absolute;
 bottom: 0;
 left: 0;
}

Declaring a width on the footer is required. If we don't do so, then browser will apply the shrink-to-fit algorithm to the footer, meaning that this element will be wide enough only to host its contents. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.