CSS scroll-state() Container Queries: :stuck and :snapped
Sticky & snapped element styling without JavaScript
Styling elements differently when they become stuck (sticky) or snapped used to require JavaScript scroll event listeners. scroll-state() container queries let CSS respond to scroll-related states directly.
The old hack vs the modern fix
View demo/* JS scroll listener approach */
const header = document.querySelector('.header');
const offset = header.offsetTop;
window.addEventListener('scroll', () => {
header.classList.toggle('stuck', window.scrollY >= offset);
});.header-wrap {
position: sticky;
top: 0;
container-type: scroll-state;
}
@container scroll-state( /* [!code ++] */
stuck: top /* [!code ++] */
) {
.header {
box-shadow: 0 2px 8px #0002;
}
}Container scroll state queries browser support
Live demo
Why the modern way wins
No scroll listeners
The browser tracks stuck and snapped states internally. No scroll event handlers, no requestAnimationFrame, no jank.
Multiple states
Query stuck (top, bottom, left, right), snapped (x, y, inline, block), and scrollable states. All with pure CSS.
Container query model
Uses the familiar @container syntax. If you know container queries, you already know how to use scroll-state queries.
- States
- stuck, snapped
- Plus scrollable
- Old Approach
- JS scroll events
- addEventListener
- Modern Approach
- scroll-state()
- Container query
How it works
Sticky headers that add a shadow when stuck, carousels that highlight the active slide: these patterns always required JavaScript. You'd listen to scroll events, calculate positions, and toggle classes. This causes layout thrashing, jank, and race conditions.
scroll-state() container queries let CSS detect scroll-related states natively. Set container-type: scroll-state on the sticky element (or the snap target) itself, then style its descendants. @container scroll-state(stuck: top) matches while that element is stuck to the top. @container scroll-state(snapped: x) matches while it is the snapped item. Only scrollable and scrolled query the scroll container. The browser handles all the tracking with zero JavaScript.