You donβt need JavaScript to detect sticky headers anymore.
Sticky Header Style on Scroll β NO JS Needed
For years, changing a header style on scroll meant JavaScript.
Scroll listeners.
State management.
Performance tuning. π
But modern CSS can now handle sticky header state changes natively.
π₯ Whatβs New?
With scroll-state container queries, CSS can detect when an element becomes sticky (stuck) and change styles automatically.
No scroll listeners.
No JS state.
No hacks.
π§ Real Use Case: Sticky Header Style Change
A common UX pattern:
π Header changes background, radius, or shadow when it sticks to the top.
Traditionally:
- JS checks scroll position
- Adds/removes a class
Handles animations
With modern CSS:CSS detects sticky state
Styles update automatically
Smooth transitions included
π§© Minimal CSS Example
.header-wrapper {
position: sticky;
top: 0;
container-type: scroll-state;
container-name: header;
}
@container header scroll-state(stuck: top) {
.header-inner {
background: yellow;
color: #232426;
border-radius: 4px;
box-shadow: 0 0 30px rgba(0,0,0,0.04);
}
}
Thatβs it. No JavaScript required. β
π HTML Markup
<header class="header-wrapper">
<div class="header-inner"></div>
</header>
Code pen Live Example
β‘ Why This Matters
- Better performance β no scroll event listeners
- Declarative UI logic in CSS
- Cleaner & maintainable code
- Built-in animations via transitions
- Great for design systems
π― Where This Pattern Shines
- Sticky headers
- Navbar transformations
- Floating toolbars
- Context-aware UI components All handled purely in CSS.
π Browser Support
- Cutting-edge feature
- Works in modern Chromium browsers
- Best used with progressive enhancement
π Next in the Series
This is Part 2 of Modern CSS That Replaces JavaScript.
Next topics:
β’ scroll-target-group logic without JS
β’ Component-level container queries
β’ CSS-driven UI interactions
π§ Takeaway
CSS is no longer just styling.
Itβs becoming a behavior layer.
Less JavaScript.
Cleaner architecture.
Better performance.
Happy styling, and thanks for reading! π
Top comments (1)
π Live demo + source code π
π CodePen Demo: codepen
π GitHub Repo: github-repo
π¬ Curious to hear your thoughts:
Would you use this in production today, or still prefer JavaScript for scroll-based UI?