DEV Community

Cover image for πŸš€ Modern CSS That Replaces JavaScript (Part 2)
Zain Muhammad
Zain Muhammad

Posted on

πŸš€ Modern CSS That Replaces JavaScript (Part 2)

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);
  }
}

Enter fullscreen mode Exit fullscreen mode

That’s it. No JavaScript required. βœ…


πŸ— HTML Markup

<header class="header-wrapper">
  <div class="header-inner"></div>
</header>

Enter fullscreen mode Exit fullscreen mode

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! πŸš€

CSS #Frontend #WebDevelopment #Performance #DevTips #UIEngineering

Top comments (1)

Collapse
 
zainmuhammad profile image
Zain Muhammad

πŸ‘‡ 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?