CSS Reference ยท Media Queries and Features
The prefers-color-scheme media feature
Reference for the prefers-color-scheme media feature: detect the user's light or dark preference, with examples, color-scheme, light-dark() and caveats.
The prefers-color-scheme media feature reports whether the user has asked their operating system or browser for a light or a dark interface. Use it to give your page a dark theme that matches the rest of the user's environment, without a toggle.
The query only reads the preference. It does not change anything by itself: you decide which colors to swap, ideally by redefining custom properties inside the query.
@media (prefers-color-scheme: dark) { :root { --bg: #111827; --text: #f3f4f6; } }
Try it
Syntax
@media (prefers-color-scheme: light) { ... } @media (prefers-color-scheme: dark) { ... }
Type: discrete. Evaluated live, so the page updates when the user switches theme.
Values
| Value | Description |
|---|---|
light |
The user prefers a light theme, or has expressed no preference. |
dark |
The user prefers a dark theme. |
no-preference |
Removed from the spec; older browsers could report it. Treat anything that is not dark as light. |
Usage notes
- Define colors as custom properties at
:root, then override them once in the media query. You avoid duplicating every rule. - Pair it with
color-scheme.color-scheme: light darktells the browser to draw form controls, scrollbars and default backgrounds in the matching scheme;prefers-color-schemeonly styles what you write. light-dark()is a shortcut. Withcolor-schemeset,color: light-dark(#111, #eee)picks the color for the active scheme without a media query. Check a compatibility table for older browsers.- A manual toggle needs more. If you let users override the system setting, set a
data-themeattribute on<html>with JavaScript and key your CSS on it, in addition to the media query. Store the choice inlocalStorageoutside sandboxed previews. - Images and shadows. Dark mode is more than swapped colors: dim bright images, soften shadows and re-check contrast.
- Contrast and accessibility. Test both themes for readable contrast. A dark theme with low contrast gray text is a common failure.
- Print. Printing normally uses a light scheme; add a
printmedia query if needed.
Browser support
Supported in all current browsers. The <meta name="color-scheme"> tag and the color-scheme property reduce flashes of the wrong theme on load.