'Don't use sticky if element is larger than screen height

I've a sidebar which is positioned sticky but in some cases larger than the height of the screen.

If the sidebar is in fact larger as the screen height, I don't want it to stick on the top. It should scroll down with the content of the page.

I'm using Bootstraps sticky-top class for that.

It has the following attributes:

.sticky-top {
    position: sticky;
    top: 0;
    z-index: 1020;
}

I changed the top: 0 to top: 50px in my case because I need the space above.

Here's some example code: https://codepen.io/cray_code/pen/ZEaOXwo

<div class="container">
    <div class="row">
        <div class="col-lg-3">
            <div class="toc sticky-top">
                <nav class="list-group">
                        Links (see example)
                </nav>
            </div>
        </div>
            <div class="col-lg-9">
                Content (see example)
            </div>
        </div>
</div>

I tried the solution from here and added the following code to my class:

.toc {
    overflow-y: auto;
    max-height: 100vh;
}

But that doesn't help.

Is there a pure CSS solution for that or do I need to use JavaScript?



Solution 1:[1]

Not sure if this is what you want, but maybe using the calc() in your css could help you.

.toc{
  overflow-y: auto;
  max-height: calc(100vh - 50px);
}

Solution 2:[2]

For aside blocks that higher then window height you can use smartSticky script Just add "data-smartsticky" atribute to your aside block https://www.npmjs.com/package/smartsticker Parent block of sticky block must be height 100%, or for flex - flex-grow:1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cs.matyi
Solution 2 Gregory Tomilin