How to implement dark mode with CSS and prefers-color-scheme
· Category: HTML & CSS
Short answer
Use prefers-color-scheme: dark to respect the system preference, and CSS custom properties to switch color palettes dynamically.
Steps
- Define a set of color variables for light and dark themes.
- Use
@media (prefers-color-scheme: dark)to override values. - Optionally add a manual toggle by applying a class to
html.
Example
:root {
--bg: #fff;
--text: #111;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111;
--text: #fff;
}
}
[data-theme="dark"] {
--bg: #111;
--text: #fff;
}
Tips
- Store the user preference in
localStorage. - Use
color-scheme: light darkto style native form controls. - Test contrast ratios in both themes for accessibility.