MarsOne
MarsOne

Reputation: 2186

Making a sticky header stick to the top

I have managed to make a dropdown for a website I am designing and I'm a bit stuck on the sticky header part..

My header has the sticky effect however when i scroll down the header does not stick to the top of the page. It always maintains a margin of 80px from the top as i mentioned in the CSS.

How can i make the header stick to the TOP when i scroll and when i scroll back to the top of the page it should retain its original position. Hope i have made myself clear.

Just pasting my CSS as the HTML is too lengthy in the fiddle.

#nav, #nav ul {
    list-style: none outside none;
    margin: 0;
    padding: 0;
    z-index:9998;
    position:relative;
}

Check this fiddle for a DEMO I have created.

EDIT: Just to be clear. I want the top:80px to be there initially. I only want the header to stick to the top while scrolling. EXAMPLE

Upvotes: 0

Views: 12424

Answers (4)

Joao
Joao

Reputation: 331

Create a .sticky class on your CSS that makes the element's position fixed, then you can easily detect if the user scrolled enough to make it stick to the top, at which point you add the .sticky class to the element. Of course when the user scrolls all the way back you should remove the class. Example:

function stick() { 
   var stickyNavTop = $('.nav').offset().top;
   var scrollTop = $(window).scrollTop();
   if(stickyNavTop > scrollTop) {
      $('.nav').addClass('sticky'); 
   } else {
      $('.nav').removeClass('sticky');
   }
}

$(window).scroll(function() {
   stick();
});

Upvotes: 0

hrkrshn
hrkrshn

Reputation: 213

Try these:

  1. Remove this from ur css to make the header stick to the top.

    #nav { .. margin:40px auto; .. }

2.css style for header - position:relative will do instead of position:fixed.

3.Put the content div inside another div and create a scrollbar only for that div. In that way, your header will always stick to the top.

Upvotes: 0

Nitesh
Nitesh

Reputation: 15779

Here you go.

WORKING DEMO

Changes in CSS:

#nav {
position:fixed;
top:-40px;
}

Upvotes: 3

Mister Epic
Mister Epic

Reputation: 16743

You have some conflicting styles you need to get rid of:

http://jsfiddle.net/5GqYh/4/

Firstly, you had top inline your header, so I set it to 0.

I also adjust the top margin on your menu, that was also pushing it down.

Upvotes: 0

Related Questions