surfitscrollit surfitscrollit - 2 months ago 6
CSS Question

How to make a header that changes position (like Pinterest)

I'm looking to make a header that begins slightly off the top of the page, with some content above it, which becomes fixed to the top of the page (and the above content disappears) when the user scrolls down. Pinterest has something that's practically identical to what I want.

Does anybody know how this can be achieved? I'm guessing this might be achieved through JavaScript, but I'd prefer an all CSS version if possible.

If this isn't possible using pure CSS, I may use something akin to this http://jsfiddle.net/Tthcu/2/ where the header is always fixed at the bottom of the page, but the disappearing content is below the header.

Thanks.

Answer

I implemented it like:

window.onscroll = function () {

    // Get the amount of scrolling.
    var top = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;

     // The menu we want to stick.
    var menu = document.getElementById("menu");

    // The thing above the menu we want to disappear.
    var menutop = document.getElementById("above_menu");

    // The height of "above_menu".
    var offset = 120;

    if (top > offset) {

        // Fix the menu to the page.
        menu.style.position = "fixed";

        // Set the margin of the disappearing element to the height of the stuck menu,
        // to replace the space lost when the menu becomes fixed.
        menutop.style.marginBottom = "32px";
    }
    else {

        // Unstick the menu.
        menu.style.position = "relative";

        // The margin underneath the disappearing element is no longer required.
        menutop.style.marginBottom = "0px";
    }
}

It works perfectly! I did have to place menu into a container div though to make it work in IE7.