Make Sticky Footer for Website Using Css

While developing web layouts, at some point you’ve probably run into this issue, This obviously broken layout happens when a footer is positioned statically at the end of the body, but the page doesn’t have much content. There is nothing to push the footer down enough and it stays in the middle of screen, leaving a huge area of white space below it.

In this quick tutorial we’re going to take a look at a modern technique for building footers that are guaranteed to stick to the bottom of the page at all times.

The Technique

To prevent the above from happening we will be building our page using flexbox, the most advanced tool CSS3 has to offer for building adaptive layouts. For those of you not familiar with the flexbox model and its properties, we will leave a couple of links at the end of the article.

Our simple demo page will have a header, main section, and a footer. Here is the HTML, nothing extraordinary there.

<body>
 <header>...</header>
 <section class="main-content">...</section>
 <footer>...</footer>
</body>

To enable the flex model we add display: flex to the body, and change the direction to column (the default is row, which is a horizontal layout). Also, the html and body will need 100% height to fill up the whole screen.

html {
     height: 100%;
}
body {
   display: flex;
   flex-direction: column;
   height: 100%;
}

We want our header and footer to take up just as much space as they need, and everything else to be reserved for the main content section. The CSS for such layout looks like this:

  header  {
     flex: 0 0 auto;
}

.main-content  {
     flex: 1 0 auto;
}

   footer {
     flex: 0 0 auto;
}

Conclusion

As you can see flexbox is a powerful ally when building layouts from scratch. All mainstream browsers support it, with a few minor exceptions, so its pretty much safe to use it in all IE9+ projects – Can i use flexbox.

Download File

Written By:

Sarmad Gardezi A blog scientist by Mind and a Passionate Blogger by heart. Sarmad is Freelancer, Entrepreneur and Google Apps Scripts Developer from Islamabad, Pakistan.

Subscribe to Email Newsletter