brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: when CSS position: sticky does not stick, check the ancestors for overflow

Css
~/tips/tip-css-position-sticky-not-sticking

position: sticky;

Three common reasons a sticky header or sidebar scrolls away anyway, and how to fix them.

position: sticky is simple until it silently does nothing. When that happens, it is almost always one of three things.

.sidebar {
  position: sticky;
  top: 1rem;
  align-self: start;
}

First, it needs an offset. Without top (or bottom, left, right) the element behaves like a relative element and never sticks.

Second, a sticky element sticks to its nearest ancestor that scrolls. If any parent has overflow: hidden, auto or scroll, that parent becomes the scroll container, and since it usually does not scroll itself, nothing happens. I’d search the ancestors in the inspector for overflow first. If you only wanted to clip content, overflow: clip does that without creating a scroll container.

Third, it can only move inside its parent. In a grid or flex row the sidebar is stretched to the full height of the row by default, so there is no room to move. align-self: start makes it as tall as its content, and then it sticks.

Support is no issue in current browsers. One thing to test though: a sticky element taller than the screen keeps its bottom part out of reach until the parent scrolls past, so keep sticky sidebars shorter than the viewport.

Further reading: MDN: position, MDN: overflow

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link