1

Good morning I am working on a sticky header for my site, I've got it working but it seems to snap into place, I want to be smooth! how do I go about this?

My site: http://www.trevorpeters.co.uk/tpwebdesign

CSS:

.sticky {  
    position: fixed;  
    width: 100%;  
    left: 0;  
    top: 0;  
    z-index: 100;  
    border-top: 0;  
}

JS

$(document).ready(function() {  
var stickyNavTop = $('.nav').offset().top;  

var stickyNav = function(){  
var scrollTop = $(window).scrollTop();  

if (scrollTop > stickyNavTop) {   
    $('.nav').addClass('sticky');  
} else {  
    $('.nav').removeClass('sticky');   
}  
};  

stickyNav();  

$(window).scroll(function() {  
    stickyNav();  
});  
}); 
2
  • Just imagine that you tell the .nav to have another class "sticky", which applies all these CSS rules to it immediately. You will either need a jQuery animation or CSS3 transition, depending on what "smooth" you actually want. Commented Nov 22, 2013 at 11:36
  • 1
    You don't even need Javascript for this. Give your header the sticky class right ahead. Commented Nov 22, 2013 at 11:38

1 Answer 1

3

By default the header is in your document flow, 'pushing' the rest of the content down. If you make it sticky, it doesn't push the rest of the document down making it snap upwards. You can fix this by making your banner sticky from the start and giving your content a top margin equal to the height of your header. This way you can just get rid of the javascript all together.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.