Tricky Sticky

Hey. It's been a while. In the past week, I have been working on my new project (Wuhuu, you will hear more about it in a sooner future) heavily. In this weekly update, I will mainly record a tricky problem I faced and felt so confused on.

The problem is the position: sticky property in CSS. This issue has a lot of answered posts on StackOverflow, but I still could not find a proper solution after a 30-minute search. In general, I understand that the problem could be caused by the overflow property, but I did not set this behavior to the parent container of my sticky component, which has the position: relative CSS property. It is not working even when I manually set overflow: visible to this parent container.

So everything becomes so strange. All answers on the internet are pointing the same thing out, but none of their solution works for me. Other than that, I feel so frustrated because I may only set overflow-x: hidden to the root container of my app, not overflow-y at all, and my sticky direction will be vertical, so it does not make sense to my brain model.

The thing is even funnier that the sticky property works on all of my previous projects, so it turns out to be an interesting issue – I made something not fine in my new architecture (with a lot of strict providers).

After comparing the CSS styles line by line between my old projects and the current project, turning styles on and off, I eventually find out the issue: one of my strict layout provider (nearly at the root) constrain the overflow horizontally. It is far away from where I was building the sticky, but it turns out that all parents of the sticky component should not set any overflow property other than visible or clip .

The original stylesheet of this layout provider was:

overflow-x: hidden; overflow-y: auto;

The original purpose was to make the layout not-scrollable horizontally and scrollable vertically. I found that keeping any of them makes sticky not working.

This trick really changes my brain model of CSS overflow: even the overflow-y: auto will affect the sticky style. But yeah actually, I should not apply this style on a layout that does not have a fixed height as it will originally be scrollable.

Finally, the stylesheet turns be this:

overflow-x: clip;

Conclusion

So, when sticky is not working, the problem may not be on the direct parent only – all parents (even the html or body ) of this component may affect its behavior if they have an overflow set.

How tricky it is.

June 17, 2022