Search code examples
jquerycsssticky

Avoid absolute positioned div from scrolling


I have two divs, absolutely positioned. One div has z-index: 1, the other z-index: 2. When I scroll the page, the second div becomes visible.

What I need is that the first div sticks to the top of the page, so that the second div slides over the first on scroll.

I tried a few things, but I did not achieve the desired result. I don't want to use fixed positioning, because the divs make a part of the interface layout; I'm afraid that making the div fixed will break the layout.

I prepared the following jsfiddle:

CSS:

*{
    margin: 0px; 
    padding: 0px; 
}

body{ 
    background: yellow; 
    height:100%; 
} 

#wrapper{ 
    position: absolute; 
    left:0;
    right:0;
    margin-left:auto;
    margin-right:auto; 
    width: 400px; 
    height: 100%; 
    background-color: blue; 
} 

#main{ 
    position: absolute; 
    top: 0px; 
    left: 0px; 
    height: 100%; 
    width: 100%; 
    background-color: red; 
    z-index: 1; 
} 

#list{ 
    position: absolute; 
    width: 100%; 
    height: 100%; 
    background-color: green; 
    bottom: -90%; 
    z-index: 2; 
} 

Solution

  • Well, you could change the value of top property of the first div via JavaScript with the respect to the position of scroll-bar in order to move the element while the page is scrolling:

    EXAMPLE HERE

    $(window).on("scroll", function() { 
        $("#main").css("top", $(window).scrollTop());
    });