csstwitter-bootstrapcss-positionbootstrap-4twitter-bootstrap-4

How to use CSS position sticky to keep a sidebar visible with Bootstrap 4


I have a two columns layout like this:

 <div class="row">
    <div class="col-xs-8 content"> 
    </div>
    <div class="col-xs-4">
    </div>
 </div>

If I set the position:sticky to the sidebar column, I get the sticky behaviour of the sidebar: https://codepen.io/marcanuy/pen/YWYZEp

CSS:

.sticky {
  position: sticky;
  top: 10px;
}

HTML:

 <div class="row">
    <div class="col-xs-8 content"> 
    </div>
    <div class="col-xs-4 sticky">
    </div>
 </div>

But when I set the sticky property only to the menu that is located in the sidebar, so the related articles section scrolls normally and gets the sticky behaviour with the menu div, it doesn't work:

 <div class="row">
    <div class="col-xs-8 content"> 
    </div>
    <div class="col-xs-4">
       <div class="menu sticky">
       </div>
    </div>
 </div>

This is the screencast of the first example scrolling the whole sidebar with a sticky behaviour, and then changing the sticky property to the menu that doesn't work:

enter image description here

Bootstrap 4 recommends the sticky property as the dropped support for the Affix jQuery plugin:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

I have tested it in:

(This is not a duplicate of How to make a sticky sidebar in Bootstrap? because that one is using BS affix)


Solution

  • I solved enabling flexbox. After raising an issue in Bootstrap's Github repository I got an answer by a Bootstrap member:

    The .col-xs-4 isn't as tall as the .col-xs-8, so there's basically no space for the Menu to "float" within when the stickiness kicks in. Make the .col-xs-4 taller and things work fine: https://codepen.io/anon/pen/OXzoNJ If you enable the Flexbox version of our grid system (via $enable-flex: true;), you get automatic equal-height columns for free, which comes in handy in your case.