0

I have an issue with a scrolling header, it starts life at the bottom of the browser, once the page scrolls down and the header reaches the top, it fixes.

The issue is when it fixes, the following div will say jump the height of the header to the top.

Here's my jQuery

var elementPosition = $('header').offset();

$(window).scroll(function(){
    if($(window).scrollTop() > elementPosition.top){
        $('header').addClass("stick");
    } else {
        $('header').removeClass("stick");
    }
});

and here's the css

.stick {
    position:fixed;
    top:0;
}
Dan
  • 1,565
  • 3
  • 23
  • 43

1 Answers1

4

The problem occurs because when making the header fixed, you are removing it from the flow of the page. In doing so, the following content "jumps" up to take its place.

One solution is to add a "ghost" div which is the same height as the header, and hidden by default.

At the point the header reaches the top of the window and you fix it in place, you also unhide the ghost div, which immediately takes its place and prevents the following content from jumping up.

Another solution is to add "margin-top" to the following content, for however tall your header is. This will have the same effect and will prevent the rest of the page content jumping.

Luke Twomey
  • 1,245
  • 1
  • 9
  • 18
  • Hi Luke that sounds like a perfects solution, can you show me a quick html / css demo – Dan Aug 13 '15 at 15:41
  • Here you go: https://jsfiddle.net/w1fs5ho5/ ghost comes in only when header has been fixed. If you then delete the ghost div from the html you'll see the "jumpiness" happening like you have now. – Luke Twomey Aug 13 '15 at 15:57
  • Thank you, a perfect solution and very smooth unlike some other methods i've tried. – Dan Aug 13 '15 at 16:00
  • Not a problem. Happy to help. – Luke Twomey Aug 13 '15 at 16:01