michelle@Internet

  1. "sticky" footer element with jQuery
    Apr 1 2012 @ 2:22 pm

    Download the code from github repository

    You’ll need one div element for all your websites content, and then a separate div element for the footer, as shown below:

    <body>
        <div class='wrapper'>
            <!--content-->
        </div>
        <div class='footer'>My Footer</div>
    </body>

    Next, you’ll need to set a height to your footer. If you don’t specify the footer’s height, it won’t work.

    div.footer { height:80px; }

    And, here’s that one line of jQuery I was talking about ;) Just stick this at the top inside the $(document).ready( function() { ... } );

    $('div.wrapper').css( 'min-height', $(window).height()-$('div.footer').height() );

    This technique is really only efficient if you’re already including jQuery in your site. Otherwise, you might have more luck than I did with the following sticky footer techniques:

    http://www.lwis.net/journal/2008/02/08/pure-css-sticky-footer/

    http://ryanfait.com/resources/footer-stick-to-bottom-of-page/

    UPDATE
    …okay, maybe not ONE line of jQuery anymore.

    The one line of jQuery above doesn’t adjust when you resize the browser. Don’t worry, it’s a super easy fix. Just add jQuery’s handy resize() function. You have to add the line before the resize() call as well, otherwise it will only work when you resize.

    $('div.wrapper').css( 'min-height', $(window).height()-$('div.footer').height() );
    $(window).resize( function() {
      $('div.wrapper').css( 'min-height', $(window).height()-$('div.footer').height() );
    });

    UPDATE 2
    Usually the first thing I do when I start building a website is body { margin:0px } . I didn’t realize at first that my sticky footer solution only works with this included. So if your footer is a tiny bit below where it should be and still causes a vertical scrollbar, try including

    body { margin:0px; }

    UPDATE 3
    If you have decided to include a border in your footer element, the width of the border may not be included in the total footer width. Therefore it is not subtracted off of the width of the window, which makes the wrapper div too large. So on a page with minimal content, a vertical scrollbar will still occur. To fix this, subtract off the width of the border from the ‘min-height’ value. So if you have a single border that’s one pixel, try this:

    $('div.wrapper').css( 'min-height', $(window).height()-$('div.footer').height()-1 );

    This is bad practice because it’s hardcoded in, but after seeing if the hardcoded value works, change the -1 to something like -$('div.footer').css('border-width'). (this will return a string, probably something like ‘2px’, which you will have to parse and convert to an integer…)

tags email github twitter tumblr resume
© Michelle Sharer 2012