CSS or JQuery Fixed sidebar in website layout

11,605

Solution 1

In the end I went with a javascript solution where I started with before I came and posted here was

<script type="text/javascript">
    $(window).scroll(function() {
        $('#sidebarPage1').css('top', $(this).scrollTop() + "px");
    });
</script>

Which did work and produced the result I wanted however it was very lacking in the effect it achieved because it was very jerky and unpleasant to watch.

I did some more googling today and came across this post: Top Floating message box using jQuery. Which lead me to here

<script type="text/javascript">
    $(window).scroll(function() {
        $('#sidebarPage1').animate({ top: $(window).scrollTop() + "px" }, 
            { queue: false, duration: 500, easing: 'easeInOutSine' });
    });
</script>

Which produces a nice clean scrolling effect of my sidebar, the easing in my opinion is what really helps it feel polished.

Solution 2

Try having your content div scroll with the content instead of expanding height wise and causing scroll bars for the whole page. That way your layout will stay the same no matter how big the content is, and the content section will get scroll bars

#content {
   overflow:auto;
}

That should work for ya.

Share:
11,605
Chris Marisic
Author by

Chris Marisic

I am the Principal Consultant of Marisic.NET specializing in user experience, software architecture, project design, and systems testing.

Updated on June 04, 2022

Comments

  • Chris Marisic
    Chris Marisic about 2 years

    My website is setup with the content structure like this

    <body>
        <div id="header></div>
        <div id="contentwrapper">
            <div id="content>
            ...
            </div>
            <div id="sidebar">
            ...
            </div>
        </div>
        <div id="footer"></div>
    </body>
    

    I'm trying to make my website behave where sidebar stays in the exact same location relative to where it would be in my static layout. That it's to the right of the Content column, that it's below the header div and above the footer div and that if they shrink the window horizontally that it doesn't move on top of the content column.

    I've tried google generic css fixed position etc and haven't been able to find anything that was really working with me so that leads me to ask here. I'm looking for how to handle this with either css or javascript, if it goes the javascript route I'd most prefer JQuery as a base.

    Edit I don't need to support archiac browsers but, I don't care if it works fully in ie6 as long as it doesn't ruin my page and degrades acceptably (like it doesn't sit on the wrong side of the page or on top my header or content)