Thursday, March 28, 2013

Fixed Position Div Vertically Only

Recently a client asked for a footer on a portal, that had a fixed width, was fixed on the screen (so it would stay on the screen when scrolling up and down), but wanted to make sure if the browser window was small enough where horizontal scrolling was needed, that the footer would scroll.

CSS position:fixed just wasn't going to cut it alone, as when you set that fixed position, it basically ignores all scrolling, both vertical and horizontal.

I ended combining CSS with some jQuery. Assuming our footer is in a div:

<div id="footer">Something in my footer</div>

I applied this CSS

.footer {
    position:fixed;
    margin:auto;
    width:900px;
    bottom:0px;
    height:30px;
}

And then I put this in my javascript file (you could put it in script tags too)


//Keeps the header and footer on the screen and scrolling horizontally
$(window).resize(positionFooter);
$(window).scroll(positionFooter);

function positionFooter() {
    if ($(window).width() < 900) {
        $('#footer').css('left', -$(window).scrollLeft());
    }
    else {
        $('#footer').removeAttr('style');
    }
}

This attaches an the function positionFooter() to the window scroll event as well as the resize event. The function itself checks to see if the width of the window is large enough to fit my footer (900 in this case) and if it isn't, it sets the left attribute as an inline style on the footer div making it move to the left simulating scrolling. If the window is large enough, it ensures the inline style tag is removed so the margin:auto will work again.

Worked like a charm.

No comments:

Post a Comment