css position sticky not working

CSS position sticky doesn’t work [SOLVED]

There could be a number of reasons why the CSS position: sticky property might not be working for you. In this article, we are sharing the most common causes for and the fix for the sticky issue.

Position sticky isn’t a new thing, but the support is now so great that I started to use it, so what’s position sticky?

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.

You must specify a threshold with at least one of toprightbottom, or left for sticky positioning to behave as expected. Otherwise, it will be indistinguishable from relative positioning.

– MDN

Wauw, isn’t that awesome? No need for JavaScript anymore when you’re building your dynamic fixed headers. So how do I use it:

.sticky {
      position: sticky;
}

Remember that you need to specify a threshold either top, right, bottom or left. Otherwise, it will be indistinguishable from relative positioning.

Checking If a Threshold Has Been Specified

A sticky element requires a threshold to be specified by setting value (other than auto) for at least one of the toprightbottom, or left properties. This threshold value makes the sticky element act as fixed positioned when it crosses the threshold, and a relatively positioned element otherwise.

.sticky {
    position: sticky;
    top: 0;
}

Checking If an Ancestor Element Has overflow Property Set

If any parent/ancestor of the sticky element has any of the following overflow properties set, position: sticky won’t work:

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

I had some issues getting it to work on an older site I did some updates on. After some “fun” investigation looking at the DOM I found out that a parent div was having overflow:hidden which means that the browser can’t calculate when the element has to be sticky.

Another gotcha but expected behavior is that once a parent with a sticky child goes out of view, the sticky element will also no longer stick.

Leave a Reply

Your email address will not be published. Required fields are marked *