Search code examples
javascriptcsspositioncss-positionfixed

Div is going behind fixed div when scrolling


I'm having a problem with the property position:fixed. If you check out my jfiddle you see, that when you scroll, and the black div hits the top, then via JS it adds the style "stick" which makes it fixed in position - as intended. Unfortunately, when I do this, and the div is getting the fixed style, the div below the black bar jumps up a bit, which ruins the idea.

The main CSS I think you have to look at is:

.orangeContent {
max-width:960px;
width:100%;
margin:0px auto;
padding:40px 0px 0px 0px;}

    header {
max-width:1920px;
width:100%;
margin:0px auto;
padding:0px;
background:#ffffff;

.stick {
position:fixed;
top:0px;
box-shadow:0px 4px 2px -2px #b32f01 ;
transition-duration:0.2s;}

And of course the Javascript:

    $(document).ready(function() {
    var s = $("header");
    var pos = s.position();                    
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();

        if (windowpos >= pos.top) {
            s.addClass("stick");
        } else {
            s.removeClass("stick"); 
        }
    });
});

So, basically, any idea on how to fix this ?

Thanks in advance.


Solution

  • This is due to the fact that the black header jumps out of the box flow, so the div below jumps up. I suggest you add the class fix to the pageWrapper instead of the header itself and then, in your css:

    .pageWrapper header{
        position: static
    }
    
    .pageWrapper div { /* the one with all the lorem ipsum */
        padding-top: 0;
    }
    
    .pageWrapper.stick header{
        position: fixed
    }
    
    .pageWrapper.stick div { /* the one with all the lorem ipsum */
        padding-top: 20px; /* needs to be set as the same height of the header */
    }
    

    I edited your fiddle to show you what I mean.

    http://jsfiddle.net/AyLNL/3/

    I used the .stick + .text selector which basically means the .text after the .stick, but I suggest you place the .text inside the pageWrapper and then go with .stick .text