CSS Sticky Header with position: sticky
Sticky headers without JavaScript scroll listeners
The old way used JavaScript scroll events and getBoundingClientRect to toggle a class. Sticky positioning does it in one property.
The old hack vs the modern fix
View demo// JavaScript: scroll listener
// (measure once: a fixed header's own rect no longer moves)
const start = header.offsetTop;
window.addEventListener('scroll', () => {
if (window.scrollY >= start)
header.classList.add('fixed');
else
header.classList.remove('fixed');
});
.header.fixed {
position: fixed;
top: 0;
}.header {
position: sticky;
top: 0;
}<!-- sticky top-0: sticks to the top edge on scroll --><header class="sticky top-0 z-10 bg-white"> Navigation</header><!-- Also works for sidebars: sticky top-4 -->Sticky positioning browser support
Live demo
Why the modern way wins
No JavaScript
The browser handles scroll. No listeners, no getBoundingClientRect, no class toggles.
Respects flow
Sticky stays in layout until it hits the threshold, then sticks. No layout jumps.
One property
Set position and top. Works for headers, sidebars, or any element you want to pin.
- Lines Saved
- 15+ → 3
- No JS needed
- Old Approach
- Scroll listener + class
- JS + getBoundingClientRect
- Modern Approach
- One property
- position: sticky
How it works
The old way meant a scroll listener, reading getBoundingClientRect on every scroll, and toggling a class to switch between normal and fixed. That's JS, reflows, and extra CSS for the fixed state.
With position: sticky and top: 0, the header stays in flow until it would scroll past the top, then it sticks. The browser does the work. No script, no class, no layout hacks.