CSS fixed position when at position x

10,688

I think this is what you are looking for: http://jsfiddle.net/QuVkV/3/

You do need to use some jQuery. In the example above, follow the div with id="bar"

Here html structure:

<div id='wrapper'>
    <div id='upper'>This is upper content</div>
    <div id='position-saver'>
        <div id='bar'>This is your facebook like button</div>
    </div>
    <div id='lower'>This is some content lower than the menu bar</div>
</div>

This is the css :

#wrapper {
    width: 100%;
    height: 2000px;
}

#upper {
    width: 100%;
    height: 100px;
}

#position-saver {
    height: 50px;
    width: 100%;
}

#bar {    
    position: static;
    height : 50px;
    width: 100%;
}

And here is the javascript :

$(document).on('scroll', function(){
    if ($('#bar')[0].offsetTop < $(document).scrollTop()){
        $("#bar").css({position: "fixed", top:0});            
    }
    if ($(document).scrollTop() < $("#position-saver")[0].offsetTop){
        $("#bar").css({position: "static", top: 0});           
    }            
});
Share:
10,688
Dennis Hackethal
Author by

Dennis Hackethal

JavaScript, Clojure, Ruby

Updated on June 04, 2022

Comments

  • Dennis Hackethal
    Dennis Hackethal almost 2 years

    I have a div positioned at the top of a page, right underneath a headline bar. As the user scrolls down and the bar goes up, I would like it go up only until the edge of the browser window and then stay there as if fixed.

    How is that possible? Is it feasible with CSS only or do I need jQuery? I would prefer jQuery for cross-browser compatibility.

    Here is the plain and simple css code I am using so far:

    #fbLikeDiv
    {
        position: fixed;
        top: 95px;
        left: 10px;
    }
    

    You can also have a look at the site: www.myskoob.com/postish/ - it is about the left Facebook like box that I would like to stay at the top edge of the browser window when the user scrolls down, but first goes up until there.