How to Fix position: sticky
release date :
- Coding
Hey there, it’s AndHA’s coding team!
In this article, we want to talk about position: sticky
, how it gets ignored, and how to fix it.
Table of Contents
What is position: sticky?
First off, position: stick
is a CSS property that literally sticks something to a part of the page.
It does this by removing itself from the flow of the page.
This is similar to position: fixed.
What’s the difference?
position: sticky
and position: fixed
both remove their element from the document flow.
However, position: sticky
is removed form the flow only within its parent container.
Below is an example of both of them at work.
See the Pen fixed + sticky by bibomato (@bibomato) on CodePen.
When position: sticky doesn’t work
When a child element with position: sticky
has a parent elements with overflow: hidden
, the position: sticky
is ignored.
Below I’ve provided an the position: sticky
property being ignored.
See the Pen fixed + sticky overflow hidden by bibomato (@bibomato) on CodePen.
Why is this?
For starters, its good to understand that this is not a bug.
The position: sticky
child element is attached to a scrolling element.
If they parent element doesn’t scroll, the position: sticky
property assumes it is in the correct position and doesn’t need to move.
How to fix it
The best solution is to avoid this situation altogether.
If its necessary, then instead of using overflow: hidden
, it is we can use contain: paint
.
contain
is a CSS property that contains a portion of the document instead of the entire document.
Here is an example of the element being larger than the width of the document, but still being contained and following the position: sticky
rules.
See the Pen fixed + sticky contain: paint by bibomato (@bibomato) on CodePen.
For more information about contain: paint
, you can read more about it in detail here.
In Conclusion
We hope you have a better understanding of the nuances of position: sticky
.
So get out there and use position: sticky
with confidence!
Until next time!