简体   繁体   中英

Make div fixed only inside another scrollable div

I have the page with structure something like this:

<div id="header"></div>
<div id="messages"></div>
<div class="content">
    <div id="sidebar"></div>
    <div id="content"></div>
    <div id="other_stuff"></div>
</div>

Header is the header of the page. Messages div is the place where I push messages. Sometimes it filled, sometimes it empty. Sidebar is navigation menu. Content is a long scrollable div. And other stuff is other stuff.

I need to make sidebar be fixed in the page on the left side when content are scrolled. But sidebar should never overlay messages and header. In other words, when I scroll down the page, header and messages are scrolled with content normally. But when I scroll up the page, sidebar should't overlay messages and header div's.

I've used CSS property position: fixed; for this but with this property sidebar overlays messages. How can I fix this with CSS and javascript/jQuery?

If I got you right, you want the sidebar to be fixed starting from a particular point.

This can be achieved through the jQuery. There are many ways, at least 3 I know. Here is the pure jQuery version i use in the cases like that (if you don't want to embed other external JS libraries)

jQuery(document).ready(function ($) {
    $fixed_id = $('#Mod128, #Mod190'); //classess or IDs of the modules you want to stick
    $(window).scroll(function(){
            if($(window).scrollTop()>254) //amount of pixels from the top of the viewport when the sticky styles applied
            {
                $fixed_id.css({position:"fixed", top:0, width:"18%"}); //sticky styles items when scroll to a particular place
            }
    });
});

Other ways of doing that are using other JS libraries, I know 2 of them:

1) jQuery Waypoints

2) stickyjs.com

Hope that helps.

Its good if you can make jsfiddle of it or else I think something like below code can help you. Fix height of your header and messages and give margin to the sidebar with total height of you header and messages.

#header, #messages {
height:3em;

} .content #sidebar { position:fixed; margin-top:3em; width:5em; } .content #sidebar { position:fixed; margin-top:3em; width:5em; }

.content #content,.content #other_stuff{
width:3em;
margin-left:5em;

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM