How to Fix CSS Position Sticky Not Working With Overflow?

#Why Does This Happen?

The sticky element does not have any room to flow within its container when the parent or any of its ancestors compute to an overflow property other than overflow: visible — i.e., one of the following:

  1. overflow: hidden
  2. overflow: scroll
  3. overflow: auto

For example, consider the following HTML/CSS which illustrates this issue:

<div id="parent">
  <div>One</div>
  <div>Two<br />has<br />extra<br />text<br />to<br />stretch<br />the<br />container</div>
  <div id="sticky">#sticky</div>
</div>
#parent { overflow: auto; }
#parent > div { display: inline-block; vertical-align: top; }
#sticky { position: sticky; top: 0; }

Following is a visual illustration of this:

#parent
  overflow: auto
One
Two
has
extra
text
to
stretch
the
container
#sticky

As you can see in this example, the sticky element has no room to scroll within its container, which is why it does not function as expected.

#How to Fix the Issue?

To fix this issue, you can do the following:

  1. Find the Parent or Ancestor Element With overflow

    You can execute the following snippet in your browser's web developer console to identify all parent/ancestor elements with overflow property set to something other than visible:

    let parent = document.querySelector('#sticky').parentElement;
    
    while (parent) {
      const hasOverflow = getComputedStyle(parent).overflow;
      if (hasOverflow !== 'visible') {
        console.log(hasOverflow, parent);
      }
      parent = parent.parentElement;
    }
    
  2. Specify height for the Overflowing Element

    Once you've identified the overflowing container elements, you must specify a height on them. For example, you can update the example from earlier like so:

    #parent { height: 100px; overflow: auto; }
    #parent > div { display: inline-block; vertical-align: top; }
    #sticky { position: sticky; top: 0; }
    

    Following is a visual illustration of this:

    #parent
      height: 100px
      overflow: auto
    One
    Two
    has
    extra
    text
    to
    stretch
    the
    container
    #sticky

This solution works the same way for a flexbox parent that has overflow property value that computes to a value other than visible.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.