prefers-color-scheme for Dark Mode
What You'll Learn
You'll discover how to detect whether a user prefers light or dark themes on their device and automatically adjust your site's colors accordingly.
Understanding prefers-color-scheme
The prefers-color-scheme media feature detects the user's system-level theme preference. Think of it like a restaurant asking "Do you prefer indoor or outdoor seating?" — you're checking what the user has already told their device they like.
Most modern operating systems let users choose between light mode (bright backgrounds) and dark mode (dark backgrounds). When they make this choice, browsers can detect it, and you can use CSS to respond automatically.
How It Works
You use prefers-color-scheme inside a media query just like min-width or orientation. It has two values:
light— the user prefers light themes (the default assumption)dark— the user prefers dark themes
Basic Syntax
/* Default (light mode) styles */
body {
background-color: white;
color: black;
}
/* Dark mode styles */
@media (prefers-color-scheme: dark) {
body {
background-color: #1a1a1a;
color: #f0f0f0;
}
}
The browser checks the user's system preference. If they've enabled dark mode, the styles inside the media query apply. If not, they get your default (light) styles.
This is automatic dark mode — no toggle switches or JavaScript needed. The site respects what users already told their device they prefer.
Why It Matters
Users who enable dark mode often do so for eye comfort, battery savings (on OLED screens), or personal preference. Supporting their choice shows respect for their needs and creates a better browsing experience.
Key Takeaway: Use @media (prefers-color-scheme: dark) to detect when users prefer dark themes and adjust your colors automatically, respecting their system-level preferences without requiring manual toggles.