Home > Software design >  Don't use sticky if element is larger than screen height
Don't use sticky if element is larger than screen height

Time:02-04

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 >
    <div >
        <div >
            <div >
                <nav >
                        Links (see example)
                </nav>
            </div>
        </div>
            <div >
                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?

CodePudding user response:

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);
}

CodePudding user response:

Hope this pen helps

Some explanations:

  • in js we use .offsetHeight&.clientHeight to get height we check weather this height(493px) 50px offset is more than screen height or not.
  • When screen size is small we set position to static
  • Also we set margin-top: 50px instead of top: 50px
    because top works only for sticky and margin-top works for static
  •  Tags:  
  • Related