Lesson 21 of 52Modern CSS
CSS Variables and Theming
Store colours and sizes in custom properties, use var() with fallbacks, scope them to components, and build dark mode with design tokens.
With layout in hand, this unit turns to the newer CSS that keeps a stylesheet easy to change. Imagine your site uses the same shade of blue in forty places: buttons, links, borders, a banner. Then the brand changes to green. Without variables you search and replace forty hex codes and hope you did not miss one. With CSS custom properties, usually called CSS variables, you change one line. Variables are also the engine behind dark mode, theme switchers and the design token systems that big companies use to keep hundreds of pages consistent. They are supported in every modern browser and need no build tool.
Declaring and using a variable
A custom property is a property whose name starts with two dashes. You declare it like any other property, inside a rule, and read it back with the var() function.
:root {
--brand: #2a6df4;
--radius: 12px;
--space: 16px;
}
.button {
background: var(--brand);
border-radius: var(--radius);
padding: calc(var(--space) / 2) var(--space);
}:root is a selector that matches the html element, the very top of the page. Declaring variables there makes them available everywhere, because custom properties are inherited: every element can see the variables of its ancestors.
A few details worth knowing early:
- Names are case-sensitive.
--Brandand--brandare two different variables. - The value can be almost anything: a colour, a length, a whole list like
0 2px 8px rgb(0 0 0 / 0.2), even a single word. - You can do maths with them through
calc(), as the padding above does. Plainvar(--space) * 2withoutcalc()does not work.
Preview
Change --brand to #2a9d4b and the border, heading and button all turn green at once. Then set --radius to 0 for a sharp, boxy look, or --space to 28px to make everything roomier.
Fallbacks
var() takes an optional second argument: a fallback used when the variable is not defined.
.alert {
color: var(--alert-text, #333);
font-family: var(--alert-font, Georgia, serif);
}Everything after the first comma counts as the fallback, so the second line falls back to Georgia, serif. Fallbacks are handy in components that might be dropped into a page without their variables, and you can nest them: var(--button-bg, var(--brand, blue)).
There is one surprise. The fallback is only used when the variable is missing, not when its value is wrong. If --alert-text is set to 20px and you use it for color, the browser does not use #333. It treats the declaration as invalid at computed-value time, and color behaves as if set to unset: it simply inherits from the parent. Even an earlier rule that set a perfectly good colour on the same element is ignored, because this declaration already won the cascade.
:root { --gap: 10px; }, what does margin: var(--size, 4px); give an element?Scope: variables follow the cascade
Because custom properties are ordinary properties, they follow the normal rules of the cascade and inheritance. A variable declared on an element applies to that element and everything inside it, and a closer declaration overrides one further up. That makes it easy to create variations of a component without rewriting it.
Preview
The .notice styles are written once. Each variation only changes --accent, and the border, background tint and label colour all follow. Add a fourth one: write .notice.warning { --accent: #e09f00; } in the style and a div with class="notice warning". (color-mix() mixes two colours and works in all modern browsers.)
Setting variables from HTML and JavaScript
You can also set a variable right in the HTML with the style attribute, such as style="--accent: purple". That is a neat way to pass one value to a component without writing a new class. JavaScript can change a variable with element.style.setProperty("--progress", "70%") and read one with getComputedStyle(element).getPropertyValue("--progress").
This splits the work cleanly: JavaScript decides the number, CSS decides how it looks. Here a progress bar reads its width from a variable, and the script only updates that variable.
Preview
Drag the slider. Then try changing the starting value in the CSS to --progress: 75%, or swap the green for var(--brand, #2a6df4) to see a fallback in action, since no --brand exists on this page.
Normally the browser treats a custom property's value as plain text, which is why it cannot animate a variable smoothly from one colour to another. The @property rule lets you register a variable with a type (for example syntax: "<color>"), an initial value and whether it inherits. Registered variables can then be transitioned. It works in all current major browsers; check Can I Use before relying on it for anything critical.
Match each piece of syntax to what it does.
Design tokens
A design token is a named design decision: a colour, a font size, a spacing step, a shadow. Instead of #2a6df4 scattered around the code, the whole team uses --color-primary. Custom properties are the natural way to store tokens in CSS, and design tools like Figma can export them.
Most token systems have layers:
Primitives are the raw palette and scales: every blue, every gray, every spacing step. They describe what a value is.
The important habit is to style components with semantic names (--color-text), not raw ones (--gray-900). A semantic name still makes sense in dark mode; --gray-900 used for text would be wrong as soon as the background turns dark.
Dark mode
Dark mode is where variables really pay off. You define your semantic colours once for light, once for dark, and every component switches automatically.
Following the system setting
Operating systems let people choose light or dark. CSS can read that choice with the prefers-color-scheme media query:
:root {
--color-surface: #ffffff;
--color-text: #1a1a1a;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--color-surface: #121212;
--color-text: #eeeeee;
}
}
body {
background: var(--color-surface);
color: var(--color-text);
}color-scheme: light dark tells the browser your page supports both, so it also darkens scrollbars and built-in form controls. There is also a newer light-dark(#fff, #121212) function that picks a value based on the colour scheme; it works in current versions of all major browsers, but check Can I Use if you need older ones.
Adding a manual toggle
Many people want a switch on the site itself. The usual pattern is a data-theme attribute on the html element, set by a little JavaScript, with CSS that reacts to it:
Preview
Click the button to flip themes. Then change the dark --primary to #ffb703 and see only the link colour change in dark mode. The profile component never mentions light or dark; it only uses the semantic names.
On a real site you combine both approaches: use the system setting by default, let the toggle override it, and save the choice in localStorage. To avoid a flash of the wrong theme when the page loads, set data-theme with a tiny script in the head, before the page is drawn.
System preference and a user toggle together
The toggle above has a flaw: it ignores the system setting. A real theme control has three states, not two. "System" follows the operating system, and "Light" and "Dark" override it. Most people never touch the control, so "System" is the default, and the site keeps following the OS even when it switches to dark at sunset.
The CSS stays small if you let color-scheme carry the choice:
:root { color-scheme: light dark; } /* System: follow the OS */
:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }
:root {
--surface: light-dark(#ffffff, #121212);
--text: light-dark(#1a1a1a, #e8e8e8);
}light-dark() returns its first value when the element's colour scheme is light and its second when it is dark. With light dark, the browser picks whichever the OS prefers, so the "System" state needs no media query at all. Setting data-theme narrows the scheme to one value and every token follows. CSS Architecture for Design Systems builds a full token set this way.
If you need to support browsers older than light-dark(), the equivalent uses a media query plus attribute selectors, and every dark token is written twice:
:root { --surface: #ffffff; --text: #1a1a1a; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --surface: #121212; --text: #e8e8e8; }
}
:root[data-theme="dark"] { --surface: #121212; --text: #e8e8e8; }Read the selectors as sentences. "Dark if the OS is dark, unless the user picked light." "Dark if the user picked dark, whatever the OS says." A build tool can generate the duplicate block for you.
Preview
Pick Dark and Light. Then pick System, and the page goes back to whatever your OS uses. Look at the text field and the select: you never styled them, yet they change too. That is color-scheme at work, which is the next section.
No flash of the wrong theme
Saving the choice is the easy part: write it to localStorage (or a cookie) when it changes. Reading it back is where sites go wrong. If the script that applies the saved theme runs in your main bundle, the browser has already painted the page in the default theme by then. A dark-mode user sees a white flash on every page load, which is worse than no dark mode.
A small, blocking inline script runs before the parser reaches the body.
The inline script must be tiny, synchronous and placed in <head> before your stylesheets or right after them. It also has to survive storage being unavailable (private modes, blocked cookies), so wrap it in try:
<head>
<meta name="color-scheme" content="light dark">
<script>
try {
const saved = localStorage.getItem("theme");
if (saved === "light" || saved === "dark") {
document.documentElement.dataset.theme = saved;
}
} catch {}
</script>
<link rel="stylesheet" href="/styles.css">
</head>Two notes for real projects. Server-rendered frameworks such as Next.js will warn that the html element's attributes differ between server and client, because the script changed them before hydration; the usual answer is suppressHydrationWarning on html, or a small library such as next-themes that injects this script for you. And if you store the choice in a cookie instead, the server can render the right data-theme straight into the HTML, so no script is needed at all. A strict Content Security Policy will block an inline script unless you give it a nonce or hash.
color-scheme: native controls and scrollbars
Your CSS colours only reach what you style. Everything else the browser draws itself: the default page background, form controls, scrollbars, the date picker pop-up, autofill highlights. color-scheme tells the browser which schemes your page supports, so it can draw those parts to match.
color-scheme: light darkmeans "I support both; use the user's preference".color-scheme: darkalone forces dark controls.- Without it, a dark page still gets bright white scrollbars and form fields, which look broken and can glare.
- The system colours
CanvasandCanvasTextfollow it, sobackground: Canvas; color: CanvasText;is a dark-mode-aware default with zero tokens. light-dark()only works whencolor-schemeis set on the element or an ancestor.
Set it in CSS on :root and also with a <meta name="color-scheme" content="light dark"> tag in the head, as above. The meta tag is read before any CSS downloads, so the browser can paint a dark background for the blank page before your stylesheet arrives. That removes one more flash.
One trap appears with iframes. If an embedded page and its parent use different colour schemes, the browser gives the iframe an opaque background in its own scheme, so a "transparent" embed can show up as a white rectangle on a dark page. Make the two schemes match.
useEffect(() => applySavedTheme(), []) in the React app. What is the best fix?Put the steps for adding dark mode to an existing site in a sensible order.
- Tap the steps below in the right order.
--color-text a better name than --black for your main text colour?Dark-mode colour pitfalls
A dark theme is not the light theme inverted. Most dark themes that look wrong fall into the same four traps.
Pure black with pure white text. #000 behind #fff gives the maximum contrast of 21:1, and on large blocks of text many readers see the letters glow or smear, especially people with astigmatism. Most product dark themes use a dark gray surface (somewhere around #121212 to #1e1e1e) and slightly off-white text. You still pass contrast easily, with less glare. Pure black can still be the right call for a deliberate design or to save power on OLED screens; just choose it on purpose.
Saturated colours vibrate. A brand blue chosen for a white background is usually too dark and too saturated on a dark one. Text in it may fail contrast, and large areas of a strong saturated colour look like they are buzzing. In dark mode use a lighter, less saturated step of the same hue: #1d4ed8 in light might become #8ab4ff in dark. That is why the token layer has separate light and dark values instead of one brand colour.
Shadows disappear, so elevation needs lightness. On white, a raised card is shown by a shadow. On near-black, a dark shadow is invisible. Dark themes show elevation by making raised surfaces lighter: the page is darkest, a card is a step lighter, a menu on top of the card a step lighter again. Give each level a token (--surface, --surface-raised, --surface-overlay) and add a subtle border where the steps are close.
Contrast must be checked again, pair by pair. Passing contrast in light mode says nothing about dark mode. Every text and background pair needs 4.5:1 for normal text and 3:1 for large text, and borders, icons and focus rings that people need to see need 3:1 (WCAG 1.4.11 Non-text Contrast). A focus ring that was dark blue on white can vanish on a dark surface. Images also need a look: a logo with dark lettering on a transparent background disappears, so ship a light version or put it on a light chip.
You can check your token pairs with a few lines of code. This is the WCAG contrast formula, run over a light and a dark theme:
Press Run (⌘ Enter) to see what happens.The light theme passes everywhere. In the dark theme the brand blue, copied over unchanged, fails as link text. Change the dark primary to #8ab4ff and run it again. Teams often run a check like this in CI over the real token file, so a token change that breaks contrast fails the build.
To look at both themes without changing your OS, open Chrome DevTools, go to the Rendering panel and set "Emulate CSS media feature prefers-color-scheme" to dark. In automated tests, Playwright takes a colorScheme: "dark" option, so your screenshot tests can cover both themes.
- custom property
- A CSS property whose name starts with two dashes, used as a variable.
- var()
- The function that reads a custom property, with an optional fallback.
- :root
- A selector that matches the html element, the usual place for global variables.
- fallback
- The second argument to var(), used when the variable is not defined.
- design token
- A named design decision, like a colour or spacing step, shared across a product.
- prefers-color-scheme
- A media query that reads whether the user chose a light or dark theme in their system.
- color-scheme
- A property (and meta tag) that tells the browser which schemes a page supports, so native controls, scrollbars and the default background match.
- light-dark()
- A function that returns its first value in a light colour scheme and its second in a dark one. Needs color-scheme to be set.
- flash of the wrong theme
- A frame painted in the default theme before the saved theme is applied, avoided with a blocking inline script in the head or a server-rendered attribute.