How does the "sticking" mechanism work during scroll?
The "sticking" mechanism (position: sticky) is based on comparing the element's position with the scroll position inside its container and switching the display mode.
It works like this:
1) Start: the element behaves like relative
The element takes up space in the flow and moves together with the page until, during scrolling, its top (or other) edge reaches the given threshold, for example:
element {
position: sticky;
top: 0;
}2) The moment of sticking
When, by the browser's calculations, the element is about to cross the top: 0 line (or top: 10px, if set that way), it stops and "sticks" to that point, as if it became fixed.
At this stage it:
- stays on screen,
- while still reserving its place in the flow (an important difference from
fixed).
3) Limited by the container
The element "sticks" only within its scrollable parent. If the container ends (the child element reaches the bottom edge of its parent), sticking stops and the element moves together with the content again.
For sticky to work, these conditions must be met
top,bottom,left, orrightis set- the parent has no
overflow: hidden|auto|scroll(otherwise sticking only happens inside that container) - the element is in the normal block flow (not
absolute, notfixed)
Short summary
- before the threshold → like
relative - after the threshold → like
fixed - within the parent's bounds → until the parent ends
The mechanism is essentially a dynamic switch of the positioning mode on the fly during scroll.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.