I'm trying to make my header fixed when the user scroll down. The problem is if the content on the page is not big enough the screen hopping. Also when I scroll to the top again it change from fixed to normal very hard. Can someone help me with this?
window.addEventListener('scroll', function() {
if($(window).scrollTop() == 0) {
$('.sticky-wrapper').removeClass('stickynow');
} else {
$('.sticky-wrapper').addClass('stickynow');
}
});
I don't really understand what 'screen hopping' means, but i guess what happens is that when your header becomes position:fixed
, it doesn't occupy space anymore so the content
moves up to fill that space an thus, 'hopping'.
You should add margin-top to your content ( or whichever element is right after the header in HTML structure ) equal to the header's height.
See below
window.addEventListener('scroll', function() { let header = $('.sticky-wrapper') if ($(window).scrollTop() == 0) { $(header).removeClass('stickynow'); $('section').css({ 'margin-top': 0 }) } else { $(header).addClass('stickynow'); $('section').css({ 'margin-top': $(header).height() }) } });
header { width: 100%; height: 100px; background: red; } .stickynow { position: fixed; background: blue; top: 0; left: 0; } section { height: 1000px; width: 100%; background: green; } body, html { margin: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header class="sticky-wrapper"></header> <section>Not 'Hopping'</section>
OPTION B. Without javascript/jQuery
If you don't need to add a class or something else that involves javascript/jQuery, you can have the same result as above, but only with css
header { position: fixed; background: blue; top: 0; left: 0; height:100px; width:100%; } section { height: 1000px; width: 100%; background: green; margin-top:100px; /*add this*/ } body, html { margin: 0; }
<header class="sticky-wrapper"></header> <section>Not 'Hopping'</section>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.