position: sticky is relative positioning with an offset the browser recomputes as you scroll:
- The box is laid out in normal flow and keeps its space, like
relative. - The browser finds the nearest ancestor scroll container. Its scrollport (the visible area), shrunk by the box's non-
autoinsets, is the sticky view rectangle.top: 0means "the top edge of that scrollport". - Whenever the box would cross an edge of that rectangle on a side with a non-
autoinset, it's shifted back inside it. - The shift stops when the box reaches the edge of its containing block, usually its parent. That's why a section heading scrolls away with the end of its section.
So debugging a sticky element that doesn't stick is checking those three inputs:
- No inset. With
top,bottom,leftandrightallauto, there's no edge to stick to; it behaves likerelative. - The wrong scroll container. Any ancestor with
overflowother thanvisibleorclipis a scroll container, evenoverflow: hidden, which never scrolls. The sticky box sticks to that ancestor, which moves along with the page, so it looks dead. Setting onlyoverflow-x: hiddenalso counts, becauseoverflow-y: visiblethen computes toauto. - No room to move. If the containing block is barely taller than the sticky box, there's nowhere to slide. A sidebar stretched to the full height of a flex or grid row is the classic case.
Two more behaviours worth naming: multiple sticky boxes in one container are offset independently, so they can overlap; and a sticky box always forms a stacking context, even with z-index: auto.