I set position: sticky; top: 0 on my sidebar and it just scrolls away with the page. No errors. What are the usual reasons?
DEV3 Developer Forum
Why is position: sticky not working on my header or sidebar?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
Sticky positioning needs a few conditions to be true. Check these in order.
1. You must set an offset
position: sticky does nothing without at least one of top, bottom, left or right. For a header, top: 0.
2. An ancestor creates a scroll container
Sticky sticks relative to its nearest ancestor with overflow set to anything but visible (hidden, auto, scroll, clip is the exception). A wrapper with overflow-x: hidden (often added to stop horizontal scroll) breaks sticky for everything inside it.
/* breaks sticky for descendants */
body, .wrapper { overflow-x: hidden; }
/* use clip instead, it does not create a scroll container */
.wrapper { overflow-x: clip; }
3. The parent is too short
A sticky element can only move within its parent box. If the sidebar's parent is only as tall as the sidebar, there is no room to stick. In a flex or grid layout the sidebar item stretches to the row height by default, which also removes the room; set align-self: flex-start.
.layout { display: grid; grid-template-columns: 260px 1fr; align-items: start; }
.sidebar { position: sticky; top: 1rem; }
4. The element is not in the scroll path you expect
Sticky works against the nearest scrolling ancestor. If your page scrolls in an inner main with overflow: auto, the header must be inside it or sticky inside that container.
5. Stacking
When the header sticks but content shows through or over it, add z-index and a background.
Tailwind version
<aside class="sticky top-4 self-start">...</aside>
<header class="sticky top-0 z-40 bg-white/90 backdrop-blur">...</header>
Pitfall
Tables: position: sticky on th works in modern browsers, but not on thead in older ones, and border-collapse: collapse can make borders scroll away; use border-separate.