surfitscrollit surfitscrollit - 1 year ago 81
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 where the header is always fixed at the bottom of the page, but the disappearing content is below the header.


Answer Source

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. = "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. = "32px";
    else {

        // Unstick the menu. = "relative";

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download