Sub topic 2
Following the system setting with prefers-color-scheme
This chapter covers the prefers-color-scheme media query: what it reports, how to write rules against it, and where it goes wrong. It assumes you know basic HTML and CSS, including selectors and the cascade. It also assumes you can read hex and rgb color values and make small DOM changes with JavaScript.
What the media query reports
Operating systems and browsers let people choose a light or dark appearance. The prefers-color-scheme media query exposes that choice to your CSS. A media query is a condition that decides whether a block of CSS rules applies. The browser checks the condition and turns the block on or off as the condition changes.
The feature accepts two values you will use:
lightmatches when the user prefers a light theme, or has not expressed a preference.darkmatches when the user prefers a dark theme.
An older draft of the spec also had a no-preference value. Browsers no longer report it, so do not depend on it. Treat light as the default and write dark as an override.
The setting comes from the operating system in most cases. On macOS, iOS, Android, Windows, and many Linux desktops, the browser reads the system appearance setting. Some browsers also let the user override it in browser settings or developer tools. Your CSS cannot tell which source produced the value, and it does not need to.
The query is live. If the system switches to dark at sunset, the browser re-evaluates the query and your dark rules apply without a page reload.
A first working example
The simplest approach is to write your light styles normally, then add a dark block that overrides them.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--link: #0b5fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--text: #e6e6e6;
--link: #8ab4ff;
}
}
body {
background: var(--bg);
color: var(--text);
}
a {
color: var(--link);
}Three things happen here.
- The
:rootrule defines three CSS custom properties. A custom property is a name that starts with--and holds a value you can reuse withvar().:rootis the<html>element, so every element inherits these values. - The media block redefines the same three names. It has the same specificity as the first
:rootrule, so the later rule wins when the query matches. - The
bodyandarules never mention a theme. They read the variables, and the variables change.
This is the main idea of the chapter. The media query appears once, near the top, and it only changes values. Your component rules stay free of theme logic.
Why the order matters
The media query adds no specificity of its own. Specificity is the rule browsers use to decide which of two conflicting declarations wins. A media query only decides whether the rules inside it exist. Inside the block, :root has the same specificity as outside it. When two rules have the same specificity, the one that appears later in the stylesheet wins.
That produces a common bug. If you put the dark block first and the light defaults after it, the light values always win, and dark mode never appears.
/* Wrong order: the light rule comes last and overrides the dark one. */
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
}
}
:root {
--bg: #ffffff;
}Write the light defaults first, then the dark overrides. If your CSS comes from several files, check the final order in the built output, since the order of imports decides the order of rules.
Overriding only what changes
The dark block does not need to repeat every variable. Variables you leave out keep their light values. This is useful for tokens that are the same in both themes, such as spacing or font sizes, and for brand colors that already work on both backgrounds.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--accent: #0b5fff;
--radius: 8px;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--text: #e6e6e6;
/* --accent and --radius are not redefined, so they stay as they are */
}
}Be careful with --accent in this example. Leaving it unchanged is only correct if #0b5fff is readable on #121212. A saturated blue like that is often too dim against a near-black background. A later chapter covers checking contrast. For now, remember that "unchanged" is a decision you should confirm, not a default you can ignore.
Applying the query without custom properties
Custom properties are the cleanest approach, but the query works on any rule. You can use it to override a single property.
.card {
background: #ffffff;
border: 1px solid #d0d0d0;
}
@media (prefers-color-scheme: dark) {
.card {
background: #1e1e1e;
border-color: #3a3a3a;
}
}This works, but it scales poorly. Each component needs its own dark block, and each block must stay in sync with the light rule above it. With 40 components you have 40 places to edit when the palette changes. Variables reduce that to one place. Use direct overrides only for one-off cases that do not fit a shared color name.
Combining the query with other conditions
Media queries can be combined with and, with commas for "or", and with not.
/* Dark and a narrow screen */
@media (prefers-color-scheme: dark) and (max-width: 600px) {
:root {
--bg: #000000;
}
}
/* Dark mode, or a request for more contrast */
@media (prefers-color-scheme: dark), (prefers-contrast: more) {
:root {
--border: #ffffff;
}
}The second example shows a trap. A comma means "or", so that block applies to anyone who prefers dark, and also to anyone who prefers more contrast, even in a light theme. White borders on a white background would disappear. When you mix queries, say out loud what each combination means before you ship it.
The not keyword negates a whole query, so @media not (prefers-color-scheme: dark) matches light users. Most code avoids it, since the "light first, dark override" pattern already covers that case.
Reading the setting from JavaScript
Sometimes JavaScript needs to know the current preference, for example to draw a chart in matching colors. Use window.matchMedia(), which evaluates the same query and returns an object with a matches boolean.
const query = window.matchMedia("(prefers-color-scheme: dark)");
function report() {
console.log(query.matches ? "System prefers dark" : "System prefers light");
}
report();
query.addEventListener("change", report);The change event fires when the setting changes while the page is open. Without the listener, your script would keep using the value it read at load time. Older Safari versions only supported the deprecated addListener() method on the returned object. If you must support those versions, check for addEventListener first and fall back.
Prefer CSS for anything that is only about appearance. Use JavaScript only when a non-CSS system, such as a canvas or a third-party widget, needs the value.
Limits of the query
The query follows the system, and that causes a set of predictable problems.
- No site-level choice. A user whose system is dark but who wants your page light has no way to say so. Query-only theming cannot offer that. A later chapter adds a manual toggle on top of this one.
- Built-in UI stays light. Form controls, scrollbars, and the default page background still use light styling unless you set
color-scheme. Your custom colors cover only the elements you style. Thecolor-schemechapter covers this. - Evaluated by the browser, not the server. Server-rendered HTML cannot see the setting in a normal request, so you cannot choose a theme on the server from this query alone. The CSS has to carry both themes.
- Printing. Printed pages usually use light settings, but this varies by browser. If you print dark pages by accident, add a
@media printblock that restores light values. - Embedded content. An iframe has its own document. It reads the preference itself, so a page you embed may switch themes independently of yours.
Verifying the result
You do not need to change your operating system to test. Browser developer tools can emulate the preference. In Chrome and Edge, open the Rendering panel and set "Emulate CSS media feature prefers-color-scheme". In Firefox, the Inspector has light and dark buttons for the same purpose. Safari's Web Inspector has an appearance toggle in the Elements tab. A later chapter covers this workflow in more detail.
A quick check is to confirm the variable value in the computed styles. Select the <html> element, view its computed or custom property values, and confirm --bg changes when you flip the emulation.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Dark block placed before the light defaults | Dark mode never applies | Put defaults first, overrides after |
| Redefining variables on `body` in one place and `:root` in another | Some elements ignore the dark values | Define all theme variables on the same selector |
| Hard-coded colors in component rules | Parts of the page stay light | Replace literals with `var()` |
| Assuming a `no-preference` value | A rule never matches | Treat light as the default |
| Only changing the background | Text becomes unreadable | Change text, borders, and link colors together |
| Reading `matches` once in JavaScript | Script falls out of sync | Listen for the `change` event |
The third row is the most common in real projects. Search your stylesheets for literal values like #fff, white, and rgb( outside your theme definitions. Each one is a spot that will not respond to the theme.
Exercise
A stylesheet defines :root { --bg: #fff; } at the bottom of the file, and above it a block @media (prefers-color-scheme: dark) { :root { --bg: #111; } }. A user with a dark system sees a white page. Why does this happen, and how do you fix it?
Show answer
The media query adds no specificity, so both :root rules have equal specificity and the later one wins. The light rule is last, so it overrides the dark one even when the query matches. Fix it by moving the light :root rule above the media block, so the dark override comes later in the file.
Exercise
You write @media (prefers-color-scheme: dark), (prefers-contrast: more) { :root { --border: #fff; } }. Name one group of users for whom this rule applies even though they use a light theme, and explain why.
Show answer
Users who use a light theme but have requested more contrast. The comma works as "or", so the block applies if either condition matches. To require both, join the conditions with and in a single query.
Exercise
Write JavaScript that logs a message every time the system switches between light and dark while the page is open.
Show answer
const query = window.matchMedia("(prefers-color-scheme: dark)"); query.addEventListener("change", (event) => { console.log(event.matches ? "dark" : "light"); });