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

荒凉一梦 提交于 2019-11-27 14:46:10

In the stable Bootstrap 4.0.0 release, this is done using the sticky-top class...

Demo

<div class="container">
    <nav class="navbar navbar-light bg-light navbar-expand">
        <a class="navbar-brand" href="#">Header</a>
        ...
    </nav>
    <div class="row">
        <div class="col-8 content">
            Content
        </div>
        <div class="col-4">
            <div class="sticky-top">
                <h4>Sticky menu</h4>
                ...
            </div>
        </div>
    </div>
    <div class="footer">
        ...
    </div>
</div>

This works even in the height of the header/navbar, content, and footer are dynamic/unknown.

https://www.codeply.com/go/QJogUAHIyg

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.

wrldbt

Polyfill explanation.

You need to include the JS polyfill in order to use it. The polyfills recommended by the link on the Bootstrap page are

Here is an updated codepen: https://codepen.io/anon/pen/zBpNRk

I included the required polyfill (I used stickyfill) and called it with

var stickyElements = document.getElementsByClassName('sticky');

for (var i = stickyElements.length - 1; i >= 0; i--) {
    Stickyfill.add(stickyElements[i]);
}

The library suggested you use this for your css

.sticky {
   position: -webkit-sticky;
   position: sticky;
   top: 0;
}
.sticky:before,
.sticky:after {
    content: '';
    display: table;
}

and finally you had the div order mixed up. You need to put the div with the sticky class outside of an entire row so I filled up the rest of the row with another <div class="col-xs-6"></div> that is empty.

The answer by @wrldbt works up to bootstrap 4 alpha 5, but in alpha 6 the -xs infix has been dropped and the grid have been rewritten.

I put something together, a bit cleaner, working with current version of bootstrap & also included a sticky footer using flexbox.

https://codepen.io/cornex/pen/MJOOeb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!