Bootstrap affix not keeping the column layout

ILikeTacos picture ILikeTacos · Aug 5, 2014 · Viewed 13.3k times · Source

When I scroll down in my browser (chrome), the right column is pushed all the way to the left, my sidebar is pushed to the background, and and all the right-side content is over the left-side sidebar.

This only happens when I apply the affix properties to my sidebar div.

If you notice, under normal situations, the page is rendered without a problem, as you can see below: enter image description here

However, when I scroll down, this is how it looks like: enter image description here

For your reference, this is how I'm implementing the affix div:

<div class="row content-wrapper">
    <div data-spy="affix" data-offset-top="200" data-offset-bottom="200" id="myAffix">
        <div class="col-lg-3">
            <!-- Sidebar code -->
        </div>
    </div>
    <div class="col-lg-9">
            <!-- content -->
    </div>
</div>

Here's a link to JS fiddle, so that you can see the problem happening live:

Here's a JS fiddle for you to see the error:

http://jsfiddle.net/fH46S/2/

How can I fix this?

Answer

David Taiaroa picture David Taiaroa · Aug 5, 2014

Here's something to get you started: http://jsfiddle.net/panchroma/H2KU7/

It still needs refinememt but the important bit is done. The key to this is than when you use affix, the Bootstrap JS applies the class of .affix to the div you are spying on after the set amount of scrolling. This affix class has the css

position:fixed;

which is what stops the div from scrolling. It also takes the div out of normal flow, which is why you get the overlap.

My solution was to wrap a new div around left hand side bar, and apply the affix behaviour to this. Your original code is was taking the <div class="col-lg-3"> out of normal flow, and that was the root of the problem.

HTML

 <div class="col-lg-3">
    <div class="wrap" data-spy="affix" data-offset-top="200" data-offset-bottom="200" id="myAffix">
       <!-- your nav div here -->
    </div> <!-- close wrap -->
  </div> <!-- close col-lg-3 -->    

EDIT
TO refine your css for the behaviour of the left hand column when it's affixed, target the left hand column with something like

.col-lg-3 .wrap.affix{
 /* custom afix padding and styling here */
}

Hope this helps!