This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/solution-to-why-css-position-sticky-is-not-working/
An issue that took far longer than it should have to solve.
I was using the CSS position: sticky
on my header so it moved down as the user scrolled. However when I added the mobile menu which transitioned in from the right, the sticky header broke. Could not understand why!
Turns out sticky
does not play nicely with most overflow
values.
If you are trying to use position: sticky
and it is not working, it is because one of the elements wrapping it is using overflow
with a value of hidden
, auto
or scroll
.
How to solve the sticky problem?
There is a new (ish) value that can be used with overflow
. It is clip
.
As Mozilla puts it in their documentation:
Similar to hidden, the content is clipped to the elementโs padding box. The difference between clip and hidden is that the clip keyword also forbids all scrolling, including programmatic scrolling. The box is not a scroll container, and does not start a new formatting context. If you wish to start a new formatting context, you can use display: flow-root to do so.
Is Clip Supported on all modern browsers.
At time of writing (23/11/2022) all current versions of modern browsers support this functionality. Take a look atCan I Use if you want to check for yourself.
Top comments (2)
Just to make it clear, the container element needs to be default value -
overflow:ย visible
. Anything apart from it will not work.It's also important to make sure that you have the height property defined for the element you are applying position:sticky to.