Dark Mode and Theme Switching
Themes can be implemented by changing semantic custom properties. The browser's prefers-color-scheme media feature can detect whether the user prefers light or dark appearance.
A robust theme system separates semantic tokens such as --surface and --text from component implementation details.
Theme Switching
Theme Tokens
:root {
--surface: white;
--text: #0f172a;
}
@media (prefers-color-scheme: dark) {
:root {
--surface: #0f172a;
--text: #f8fafc;
}
}
body {
background: var(--surface);
color: var(--text);
}💡 The same component styles consume semantic tokens while the token values change for dark mode.
Key Takeaways
- Separate semantic tokens from component rules.
- Use
prefers-color-schemefor system preference detection.
Knowledge Check
Which media feature detects a user's preferred color scheme?