DEV Community

WDSEGA
WDSEGA

Posted on

Dark Mode Toggle

One button, two worlds. Dark mode toggle is a standard feature of modern websites — but 90% of implementations ignore the golden combo of prefers-color-scheme and CSS variables. Today we build a perfect dark mode toggle from scratch.

What Is It

Dark Mode Toggle lets users switch between light and dark themes. A good implementation needs:

  • Follow system preference for initial theme
  • Persist user's manual choice to localStorage
  • CSS variable driven, zero JS style manipulation
  • Smooth transition animation, no flash

Code Breakdown

CSS Core: Variable Driven

All colors use CSS variables. Switching only changes the data-theme attribute — the browser handles repainting automatically.

Icon Animation

The sun uses 8 box-shadows to simulate rays; the moon uses one offset shadow to "bite" a portion, creating a crescent.

JavaScript: Three-State Logic

Priority: localStorage > prefers-color-scheme > default light. Also listens for system theme changes.

Key Technical Points

  1. CSS variable driven: No style property manipulation, only data-theme change — optimal performance
  2. Three-state priority: localStorage > prefers-color-scheme > default light
  3. Anti-flash: Inline initialization script in <head> to prevent FOUC

Common Pitfalls

  • FOUC flash: Inline execute applyTheme in <head> before any CSS renders
  • iframe inheritance: Each iframe has its own documentElement
  • box-shadow calculation: Sun ray shadows need precise offset and spread
  • Safari compat: prefers-color-scheme requires Safari 12.1+

更多Web组件,请访问 Web组件字典


Read the full bilingual version at Deskless Daily.

Top comments (0)