Dark Mode with prefers-color-scheme
Implement automatic dark mode using the CSS prefers-color-scheme media feature. Detect user OS theme and apply matching styles.
Detailed Explanation
Automatic Dark Mode with prefers-color-scheme
The prefers-color-scheme media feature lets you detect whether the user prefers a light or dark color theme based on their operating system or browser settings.
The Query
@media (prefers-color-scheme: dark) {
:root {
--bg: #0a0a0b;
--text: #fafafa;
--border: #27272a;
}
}
How It Works
Modern operating systems (macOS, Windows, iOS, Android) let users choose a system-wide theme. Browsers expose this preference through prefers-color-scheme, which accepts two values:
- dark -- the user prefers a dark background with light text
- light -- the user prefers a light background with dark text
Implementation Pattern
The most maintainable approach uses CSS custom properties:
:root {
--bg: #ffffff;
--text: #18181b;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0a0a0b;
--text: #fafafa;
}
}
body { background: var(--bg); color: var(--text); }
Combining with a Manual Toggle
Many sites pair the media query with a JavaScript toggle that adds a .dark class. Tailwind CSS supports this with its darkMode: "class" strategy. The media query provides the default, while the class toggle lets users override it.
Browser Support
prefers-color-scheme is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. It has been available since 2019.
Use Case
Use this query when you want your website to automatically switch between light and dark themes based on the user's operating system preference, without requiring a manual toggle.