Detecting Dark Mode with prefers-color-scheme
Learn how to detect the user's preferred color scheme (dark or light) using CSS media queries and JavaScript matchMedia, with implementation examples.
Detailed Explanation
prefers-color-scheme
The prefers-color-scheme media feature detects whether the user has requested a dark or light color theme through their operating system settings.
CSS Usage
/* Light mode (default) */
body {
background: #ffffff;
color: #1a1a1a;
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
body {
background: #0a0a0b;
color: #fafafa;
}
}
JavaScript Detection
const isDarkMode = window.matchMedia(
'(prefers-color-scheme: dark)'
).matches;
console.log('Dark mode:', isDarkMode);
Listening for Changes
Users may toggle dark mode while your app is open:
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', (e) => {
if (e.matches) {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
});
Using CSS Custom Properties
A clean approach for theme switching:
:root {
--bg: #ffffff;
--text: #1a1a1a;
--primary: #2563eb;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0a0a0b;
--text: #fafafa;
--primary: #3b82f6;
}
}
body {
background: var(--bg);
color: var(--text);
}
User Override Pattern
Allow users to override the system preference:
function getTheme() {
const stored = localStorage.getItem('theme');
if (stored) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark' : 'light';
}
Browser Support
Supported in all modern browsers since 2019 (Chrome 76, Firefox 67, Safari 12.1, Edge 79).
Use Case
Web developers implementing dark mode need to detect the user's system preference, apply the correct theme, and listen for real-time changes when the user toggles their OS appearance settings.
Try It — Screen Info Display
Related Topics
Respecting prefers-reduced-motion for Accessibility
Media Queries
Using pointer and hover Media Queries
Media Queries
CSS resolution Media Query for High-DPI
Device Pixel Ratio
Tailwind CSS Responsive Breakpoints Reference
Responsive Breakpoints
Viewport Size vs Screen Resolution: Key Differences
Viewport & Screen