Solved

position: sticky does nothing and I cannot work out why

Asked by Daniela Rocha · 1K views · 2 replies

Daniela Rocha8 messages · 2 solutions

Standard sticky sidebar. position: sticky; top: 0; on the element, it has a height, the parent is taller than it, and it just scrolls away like it is static. No errors, nothing in devtools looks wrong.

It works in a codepen with the same CSS, so it is something about my page, but I cannot find what.

2 replies

Kenji MoritaSolution

Look up the tree for overflow on an ancestor. Any ancestor with overflow: hidden, auto or scroll becomes the scroll container for the sticky element, and if that container is not the thing being scrolled, the element has nothing to stick to. It silently does nothing — no warning anywhere.

The usual culprit is a global rule somebody added to stop horizontal overflow:

html, body { overflow-x: hidden; }

Replace it with clip, which prevents the same overflow without creating a scroll container:

html, body { overflow-x: clip; }

To find it, paste this in the console with the sticky element selected in devtools:

let el = $0;
while ((el = el.parentElement)) {
  const o = getComputedStyle(el).overflow;
  if (o !== 'visible') console.log(o, el);
}

Second most common cause, for completeness: the parent has display: flex and the sticky child is being stretched to full height, so there is no room left for it to move within.

Link
Daniela Rocha

It was overflow-x: hidden on body, added months ago by someone chasing a horizontal scrollbar. clip fixed both. That console snippet is going in my notes.

Link