🎨 Fix a Sticky Header Jumping When a Scrollbar Appears
`position: sticky` keeps an element pinned relative to its nearest scrolling ancestor, but when page content grows tall enough to introduce a vertical scrollbar for the FIRST time, a browser using a classic non-overlay scrollbar reduces the viewport’s available width by the scrollbar’s own width at that exact moment. A sticky header sized with `width: 100vw` was already laid out against the wider, scrollbar-less viewport, so it visibly jumps the instant the scrollbar appears, because `100vw` always measures the full viewport including the scrollbar gutter, while the rest of the page’s `width: 100%` does not.
🔎 The Problem
.sticky-header {
position: sticky;
top: 0;
width: 100vw; /* includes the scrollbar gutter - jumps when one appears */
}
/* Fix: measure against the containing block, not the raw viewport */
:root {
scrollbar-gutter: stable; /* reserve the gutter before it's ever needed */
}
.sticky-header {
position: sticky;
top: 0;
width: 100%;
}
✅ Fix: Stop Measuring Against the Raw Viewport
- Replace any `width: 100vw` on the sticky header (or its full-bleed children) with `width: 100%`, since `100%` resolves against the actual containing block after the scrollbar is already accounted for, while `100vw` always measures the full viewport including the scrollbar gutter.
- Set `scrollbar-gutter: stable` on the scrolling ancestor so the browser reserves the scrollbar’s width up front, even on pages that don’t yet have enough content to need one — removing the layout shift at its source instead of patching around it.
- For older browsers without `scrollbar-gutter` support, force a permanent scrollbar with `overflow-y: scroll` instead of the default `auto`, trading a scrollbar that’s always visible for one that never causes a width jump when it appears.
🚨 Why This Is Dangerous
- A header that jumps the instant a scrollbar appears often does so right as a user is mid-click on a nav link or button in that header, and the sudden shift can cause a mis-click on a different link than the one they aimed for.
A viewport unit and a percentage only agree with each other until a scrollbar shows up to disagree.
