Domanda

I got this site at http://www.f7tek.tk. The site has a white menu bar.

enter image description here

What i want is, when i scroll down the page this bar sticks on the top:

Like so: i.stack.imgur.com/LKPnY.png

I tried setting the position to fixed and setting the z-index to 1000. That does almost everything I want but When I scroll down the bar stays at that position, doesn't move to the top like i wanted.

Is it possible using CSS only? what about JavaScript? If it is, then how?

È stato utile?

Soluzione

What you want to do is to add a class to your header bar if you scroll to a certain point.

So if you have a header called <div class="sticky-header">Your header</div> and add a second class called fixed that will be applied after scrolling to 100px from the top of the window it will stick from there.

JQUERY:

$(window).scroll(function(){
    if ($(window).scrollTop() >= 100) {
       $('.sticky-header').addClass('fixed');
    }
    else {
       $('.sticky-header').removeClass('fixed');
    }
});

CSS:

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; 
}

JSFIDDLE DEMO

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top