Search code examples
csspositioningfootersticky-footer

Footer bottom of page CSS


In this fiddle I want to create a footer that stays at the bottom of the page, as in this screenshot:

Footer

However, when the browser window is minimized so that the viewport is less than the content area, and the page is scrollable, the footer stays in the middle of the page rather than below the content. Once a user scrolls, the footer stays in the middle of the content boxes, like in this screenshot:

Footer scrolled

How do I create a footer that stays at the bottom of the viewport when there is no scrollbar, but then stays at the bottom of the content boxes when a scrollbar appears and content is outside the viewport?

I am using position:absolute; bottom:0; on the footer. Do I need to add declarations to my content box, or to the footer? Thanks for your help!


Solution

  • There are a lot of attempts to do this via CSS, most are hacky workarounds, and honestly its WAY easier to do with Javascript. But for pure CSS, it usually goes something like this:

    1) Setting * to border-box:

    * {
        -webkit-box-sizing:border-box;
        -moz-bos-sizing:border-box;
        box-sizing:border-box;
    }
    

    2) Set footer to position:absolute, with fixed height:

    #footer {
        position:absolute;
        left:0;
        right:0;
        bottom:0;
        height:40px;
    }
    

    3) Set html,body, and your container to height:100%, min-height:100%, and your container position to something other than static, and padding-bottom to whatever your footer height is + a little gap (if you want):

    html,body,#container {
        height:100%;
        min-height:100%;
    }
    
    #container {
        position:relative;
        padding-bottom:50px;
    }
    

    This should handle it decently well for IE8 and above. For IE7 and below ... well that gets pretty damn tricky, you can google that one if you'd like. :) Some notes:

    1. The box-sizing declaration is needed to ensure height of 100% includes padding (otherwise it would just be 100% plus the padding you gave it).
    2. when position:absolute is used on a child element, position other than static must be declared on the parent for the childs position to be relative to the parent, otherwise it will be the first parent up the DOM tree with position other than static (in this case, it will just be the window).