Search code examples
csspositioning

Fixed footer that won't go past bottom of content


I am trying to get a footer that will always stay at the bottom of the viewport if the content is longer than the viewport. If the content doesn't stretch to the bottom of the viewport, then the footer will stay at the bottom of the content.

Here's my HTML:

<div id="wrapper">
    <!-- variable content and other divs in here -->
    <div id="footersurround">
        <div id="footerparent"> 
            <div id="footer"></div>
            <div id="linkshome"><!-- links in here --></div>
        </div>
    </div>
</div>

And CSS:

#wrapper {
    position: absolute;
    left: 50%;
    width: 1024px;
    margin: -512px;
    margin-top: 8px;
}

#footersurround {
    position: fixed;
    top: 0;
    max-width: 1024px;
    width: 100%;
    height: 100%;
    max-height: inherit; /* I want this to take the same value as the wrappers height if I set it to a value(e.g 768px) it works perfectly but when setting it to inherit it will stretch the whole viewport even if the wrapper does not*/
}

#footerparent {
    position: absolute;
    bottom: 0;
    width: 100%;
    z-index: 30;
}

#footer {
    position: absolute;
    bottom: 0;
    margin: 0 auto;
    min-height: 60px;
    width: 1024px;
    background-color: black;
    opacity: 0.50;
    filter: alpha(opacity=50); /* For IE8 and earlier */
    z-index: 16;
}

#linkshome {
    position: absolute;
    bottom: 0;
    margin: 0 auto;
    margin-top: -47px;
    min-height: 47px;
    width: 100%;
    max-width: 1074px;
    z-index: 17;
    text-align: center;
    font-size: 24px;
    font-family: Verdana;
    color: white;
}

Solution

  • The key would be to compare viewport height with document scroll height and set the footer's position (absolute or fixed) accordingly. Here's something I knocked up (jQuery assumed).

    <head>
        <script src='jquery.js'></script>
        <script>
        $(function() {
            var footer = $('footer'), doc = document.documentElement || document.body;
            footer.css('position', doc.scrollHeight <= $(window).height() ? 'absolute' : 'fixed');
        });
        </script>
        <style>
        body { margin: 0; }
        section { height: 600px; margin-top: 50px; border: solid 1px; position: relative; padding: 10px 10px 40px 10px; }
        footer { bottom: 0; width: 100%; height: 30px; background: red; left: 0; }
        </style>
    </head>
    <body>
        <section>
            <h1>main content here</h1>
            <footer></footer>
        </section>
    </body>