How can I make a sticky element stay within its scrolling section?
Quick answer
Give the element position: sticky and a non-auto inset on the axis where it should stick, such as top: 1rem. Then inspect its ancestors: the nearest ancestor with a scrolling mechanism can determine what sticky responds to. Sticky positioning is also relative to its containing block, which helps determine the area in which it can stick. [S1]
The question, the details, the next step.
A practical checklist
Set
position: stickyon the element.Set a non-
autoinset on the axis where it should stick.Inspect ancestors for
overflow: hidden,scroll,auto, oroverlay.Identify the element’s containing block and whether it is the intended section.
Test changes one at a time while scrolling through the section.
A few more useful answers
Does `top: 0` matter if I already set `position: sticky`?
Yes. For vertical sticking, use a non-auto inset such as top: 0. Without one on that axis, sticky behaves like relative positioning there. [S1]
Can an ancestor with `overflow: hidden` affect sticky positioning?
Yes. An ancestor with overflow: hidden can establish the scrolling mechanism sticky uses, even if it is not the element you think of as the scroller. [S1]
Will this example work unchanged in every layout?
Not necessarily. The example illustrates an inset, ancestor relationships, and a containing block; it does not establish behavior for every surrounding layout or stylesheet. [S1]
Sources
References used for this guide.
- [S1] position CSS property - CSS | MDN developer.mozilla.org · Checked
