Custom properties
What CSS custom properties are, how they differ from preprocessor variables, how they inherit and cascade, and the patterns that make themes cheap.
Custom properties
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A custom property is a property you name yourself, starting with `--`. You read it with `var(--name)`. It participates in the cascade and inherits like `color` does.
- Unlike a Sass variable, it exists at runtime in the browser: it can change inside a media query, on one element, or from JavaScript, and everything that uses it updates.
- Where you declare a property decides who sees it. `:root` makes it global, and declaring it on a component scopes it to that component and its descendants.
- `var(--x, fallback)` supplies a value when the property is not defined. That makes `var()` with a fallback the usual way to expose a customisation point on a component.
- A property that resolves to something invalid for where it is used becomes invalid at computed-value time, so the declaration falls back to the inherited or initial value, not to the previous rule.
The problem: repeating yourself
A site uses one brand colour in thirty places. Changing it means searching and replacing thirty values, and hoping nobody typed it slightly differently. Preprocessors solved this years ago with variables, but those vanish when the stylesheet is compiled. The browser never sees them, so they cannot react to anything that happens on the page.
Custom properties are variables that live in the browser. They are properties like any other, so they follow the cascade and inheritance rules from earlier in this roadmap.
Declaring and using
:root {
--brand: oklch(55% 0.2 260);
--space: 1rem;
}
.button {
background: var(--brand);
padding: var(--space) calc(var(--space) * 2);
}
Names start with two dashes and are case-sensitive. :root is the <html> element, so everything inherits from it. Any value is allowed as the declared value, even a fragment like 0 0 10px or (min-width: 40em), and it is substituted where var() appears. calc() works with it.
They inherit
This is the thing that makes them more than find-and-replace. A custom property inherits down the tree, and the nearest declaration wins:
:root { --accent: navy; }
.card { --accent: tomato; }
.card a { color: var(--accent); } /* tomato inside cards, navy elsewhere */
You can re-skin a whole subtree by setting a handful of properties at its root. That is the idea behind theming:
:root { --bg: white; --fg: #111; }
:root.dark { --bg: #111; --fg: #eee; }
body { background: var(--bg); color: var(--fg); }
Flip the class, and everything that references those properties recomputes. The user preference queries lesson applies the same trick to prefers-color-scheme.
Fallbacks and component knobs
var() takes a fallback as its second argument:
.button {
background: var(--button-bg, var(--brand));
border-radius: var(--button-radius, 0.5rem);
}
The component works with no setup. A page that wants rounder buttons sets --button-radius on a section. The author of the component has published a small, documented customisation surface, without anyone needing a more specific selector to override it. Because overriding happens with inheritance rather than specificity, it also avoids most of the fights the specificity lesson describes.
Changing them from outside CSS
document.documentElement.style.setProperty('--mouse-x', event.clientX + 'px');
getComputedStyle(el).getPropertyValue('--space');
JavaScript can read and write them like any property, which lets script pass data into CSS (a pointer position, a percentage, an item index) without rewriting class names. For a list, setting style="--i: 3" on each item and using calc(var(--i) * 80ms) for an animation delay is a common pattern.
They can change in media queries
:root { --gutter: 1rem; }
@media (min-width: 60em) { :root { --gutter: 2rem; } }
Everything that uses --gutter follows. One place to change a spacing scale beats finding every rule that sets padding.
Invalid at computed-value time
If --size holds red and a rule says width: var(--size), the browser accepts the declaration when parsing, because it cannot know what var() will contain. At the time it computes values, it finds red is not a width. The result is not “ignore this rule and use the one before”. The property becomes its inherited value if it inherits, or its initial value otherwise. This quirk makes bad values hard to spot, which is why the Computed pane in DevTools is useful, and it is one reason to register a property’s type with @property, covered a few lessons on.
Not just for colours
Spacing scales, font stacks, durations, easing curves and shadows are all good candidates. Resist wrapping every value in a variable. A property is worth creating when the value is used in several places, or when something should be able to override it. Locally scoped properties, like --_size set on one component, are fine and cheap.
What the video covers
Kevin Powell’s “CSS Variables - An introduction to CSS custom properties” is from December 2017 and runs about 12 minutes. From its title it is an introduction to the feature, so it should cover declaring and using variables. The feature has not changed since then, but I could not read a transcript, and the description gave no timestamps, so which examples it uses is not described. The scoping, fallback and computed-value details here come from the specification and MDN. His 2023 follow-up on using custom properties for more than :root variables is in further viewing.
Where this fits
Custom properties connect straight to the cascade and inheritance you already know from specificity and the cascade. Next is nesting, and later @property, which gives a custom property a type, and the architecture lessons later in this roadmap lean on them for design tokens.
Check yourself
A `.card` sets `--accent: tomato`. A `<button>` inside the card uses `color: var(--accent)`. The page also sets `--accent: navy` on `:root`. What colour is the button text and why?
Tomato. A custom property inherits down the tree, and the closest declaration wins. The button inherits `--accent` from `.card`, not from `:root`, so the card's value shadows the global one for everything inside it.
How does a custom property differ from a Sass variable like `$brand`?
A Sass variable is replaced at compile time and does not exist in the output CSS, so it cannot change per element or at runtime. A custom property is real CSS, resolved by the browser per element, so it can be overridden in a media query, scoped to a component, changed with `element.style.setProperty`, and inherited.
What does `padding: var(--space, 1rem)` do when `--space` is not set anywhere above the element?
It uses the fallback, `1rem`. This is how a component offers an optional knob: the default works, and any ancestor can set `--space` to change it.
If `--size: red` and you write `width: var(--size)`, what is the width?
`width` ends up as its inherited-or-initial value (for `width`, `auto`). The custom property itself was valid because any tokens are allowed, but the substituted value is not a valid width, so the declaration is invalid at computed-value time and does not fall back to an earlier `width` rule.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.