π What is light-dark()?
light-dark() is a modern CSS color function that automatically selects one of two colors depending on whether the user's system is inlight mode or dark mode.
Note
β Works with any color format (hex, rgb, hsl, lab, p3, color(), etc.)
π― Why Use light-dark()?
- Automatically adapts components to system theme
- Removes the need for @media (prefers-color-scheme)
- Cleaner and more expressive syntax
- Perfect for text, backgrounds, borders, shadows, and icons
π Syntax
light-dark Syntax
light-dark(<light-color>, <dark-color>)The first color is used in light mode. The second color is used in dark mode.
π Example 1 β Adaptive Background
Background Example
.card {
background: light-dark(white, #1a1a1a);
}Automatically switches to dark gray in dark mode.
ποΈ Example 2 β Text Colors
Text Example
.title {
color: light-dark(#111, #f5f5f5);
}Ensures good readability in both modes.
π¨ Example 3 β Borders & Shadows
Border & Shadow Example
.box {
border: 1px solid light-dark(#ccc, #444);
box-shadow: 0 2px 6px light-dark(#0002, #fff2);
}Both border and shadows adapt intelligently.
π Compare: With vs Without light-dark()
| Old Way | New Way (light-dark) |
|---|---|
| @media (prefers-color-scheme: dark) { .box { background: #222; } } .box { background: #fff; } | background: light-dark(#fff, #222); |
Note
π± Example 4 β Icons & SVG Colors
SVG Fill Example
svg {
fill: light-dark(#333, #ddd);
}Icons automatically adapt when OS theme changes.
π¨ Using Variables with light-dark()
Using CSS Variables
:root {
--brand-light: #6200ee;
--brand-dark: #bb86fc;
}
.button {
background: light-dark(var(--brand-light), var(--brand-dark));
}Great for building theme systems with consistent brand colors.
π₯ Example β Full Adaptive Component
Full Component
.card {
background: light-dark(#fff, #111);
color: light-dark(#111, #eee);
border-color: light-dark(#ddd, #333);
}
.card:hover {
background: light-dark(#f6f6f6, #1a1a1a);
}A card that fully adapts to light/dark themes, including hover states.
π§ How light-dark() Works Internally
| Mode | Output |
|---|---|
| Light Mode | Returns the FIRST color |
| Dark Mode | Returns the SECOND color |
Note
β οΈ Common Mistakes
- β Forgetting that order matters (first = light, second = dark)
- β Expecting gradual changes (itβs a direct switch)
- β Using invalid color formats (must be valid CSS colors)
- β Using outdated browsers without fallback
Note
π₯ Summary
light-dark() is the simplest and cleanest way to create adaptive color themes in modern CSS. It eliminates the need for color-scheme media queries and makes your UI instantly responsive to system preferences.
Learn more βMDN Docs π