Development · Tip
Dynamic Theming with CSS light-dark() and color-scheme
CSS pattern for switching colors across themes without duplicate selectors
This CSS recipe combines the light-dark() color function with the color-scheme property to manage theme-dependent styling cleanly. By setting color-scheme at the root and overriding it with a data attribute, elements automatically resolve appropriate light or dark palette values inline.
How it works
html { color-scheme: light dark; }
[data-theme=light] { color-scheme: light; }
[data-theme=dark] { color-scheme: dark; }
h1 { color: light-dark(red, orange); }
Tweet also links to an earlier explainer: https://x.com/jh3yy/status/1803208308741820603/video/1
What it's for
- Implement light and dark mode styles without writing duplicate selector blocks
- Pair with custom theme-toggle animations and View Transitions
- Respect system-level color preferences while supporting manual user overrides
Key points
- Defines default browser color-scheme support using light dark on root
- Enables explicit theme overrides using data-theme attributes
- Provides inline light-dark(lightColor, darkColor) declarations on individual selectors
- Removes the need for separate CSS variable overrides per theme block
Pricing
Free
Details
- Type
- Tip
- Category
- Development
- Topic
- CSS Recipes
- Open source
- No
- Platforms
- Web
- For
- Front-end developers and web designers
- Alternative to
- Prefers-color-scheme media query overrides, CSS variable swapping via class names
- Tags
- css, theming, dark mode, front end, web design
Why it was saved
- @jh3yy: Kept as the paired recipe: light-dark() handles theme-dependent colors without writing duplicated selectors, complementing the flicker View Transitions trick.
Related
Visual generator for creating organic blob shapes using CSS border-radius
CSS technique for flickering theme transitions using View Transitions and linear() curves
React component library for Apple-style liquid glass and blur effects.
CSS recipe for interactive 3D card tilt and 2D layer parallax
CSS technique for dynamic, semi-transparent borders using background-clip and backdrop-filter
HTML technique to switch browser favicons based on system color scheme
Updated