Posts tagged "sass"

A Post Entitled Conditionally absolute

posted 2 years ago in rails css sass jquery

I like footers, well, that appear at the foot of the page. I guess that seems obvious enough but what I really mean is a bit more specific. If I have a ‘short’ page in which the page content only extends halfway down the bottom of the browser window (viewport) then I want the footer pushed to the bottom of the viewport. If I have a ‘long’ page where the content scrolls past the bottom of the viewport then the footer should just appear at the end of the content.

I could probably wait for the footer tag coming in HTML 5. I do not know, however, if rendering engines will widely adopt my wishes for footer placement. Moreover, I don’t particularly care to wait for widespread implementation of HTML5 across browsers, particularly those ‘non-modern’ browsers that are likely to dominate my user base. I need the answer now.

Absolute positioning

Absolute positioning would seem to be a great answer. But it’s not. I tried the following (haml/sass):


#footer{:style=>'position: absolute; bottom: 0;'}

This solution worked very well for the ‘short’ page on which I first tested it and I was actually pretty happy with it. The page renders with blank space between the end of the content and the nearly-black 3em footer. The problem is that it had the exact opposite effect of not positioning the footer absolutely. Specifically, with long pages I now have the footer stuck in the middle of the content (rather than in the middle of a short page with blank space trailing the footer). Back to the drawing board.

Conditional absolutes

Really I had the two pieces that I needed in place. For long pages I could let the footer stay in place at the end of the content. For short pages I could force it to the bottom of the viewport. If only I could switch between the two…

Which of course I could, with jquery. Actually it took jquery and an additional class on the footer div. The styling for the additional class contains the style that I was applying inline above. Specifically: (sass)


#footer.floor
  :position absolute
  :bottom 0

Having created that simple class I then added the following jquery snippet to my $(document).ready function:


    if ( $(window).height() > $('body').height() ) {
        $('#footer').addClass('floor');
    } else {
        $('#footer').removeClass('floor');
    }

This code simply compares the height of the ‘body’ (the content) to the height of the viewport. If the content is shorter than the viewport then we add the ‘floor’ class to the footer, adding the absolute positioning to the bottom of the viewport for ‘short’ pages. If the content is longer than the viewport then we remove the ‘floor’ class (just in case it had been added previously) and let the footer sit at the end of the content.

Comments

About this site and its Author


The Tumblrs to Follow

  • staff
  • cdmwebs
  • paulsullivanjr
  • dawnvanasse
  • bitbltr