Sub topic 2
Declaring and using custom properties
This chapter covers the mechanics every later chapter relies on: how to declare a CSS custom property and how to consume it with var(). It assumes you know basic CSS selectors, properties and values, and that you have a working idea of the cascade and specificity. You also need to know how to link a stylesheet to an HTML page. The chapter on cascade and inheritance goes deeper on how values resolve. Here you only need enough of that to predict where a declared property is visible.
What a custom property is
A custom property is a property whose name you choose. The name must start with two hyphens. You declare it like any other property, inside a rule, and you read it with the var() function.
:root {
--brand-color: #2563eb;
--gap: 8px;
}
.alert {
border: 2px solid var(--brand-color);
padding: var(--gap);
}Custom properties are the storage layer for design tokens in CSS. A design token is a named design decision, and a custom property gives that name a value the browser can resolve at runtime. Because the browser resolves them while the page is live, you can change them with a media query, a class, or JavaScript. Preprocessor variables such as Sass $gap are replaced at build time and cannot do that.
Declaration syntax
A declaration has three parts: the name, a colon, and a value.
:root {
--space-md: 1rem;
--font-body: "Inter", system-ui, sans-serif;
--shadow-card: 0 1px 2px rgb(0 0 0 / 0.2), 0 4px 12px rgb(0 0 0 / 0.1);
}These rules apply to names:
- The name starts with
--. A name such as-gaporgapis not a custom property. - After the dashes you can use letters, digits, hyphens and underscores. Non-ASCII characters are also allowed.
- Names are case-sensitive.
--Gapand--gapare two different properties. The standard CSS properties you know, such asColor, are case-insensitive, so this catches people out. - Pick lowercase names with hyphens and stay consistent. The naming chapter covers conventions in detail.
The value is far less restricted than a normal property value. The browser does not check it against any property's grammar when you declare it. It stores the value as a sequence of tokens, which are the small pieces the CSS parser reads, such as numbers, identifiers and punctuation. This is why all of these are legal declarations:
:root {
--columns: 3;
--border-width: 1px;
--border-style: solid;
--transition-fast: 150ms ease-out;
--not-a-real-value: banana 42 !!;
}The last line is accepted as a declaration because nothing checks its meaning. A problem only appears when you use the value somewhere that cannot accept it.
Where to declare a property
You can declare a custom property in any rule. The selector decides which elements can use it, because custom properties inherit by default. An element sees the properties declared on itself and the ones it inherits from its ancestors.
Declaring on :root makes a property available to the whole document. :root matches the html element and has higher specificity than a plain html type selector, which can matter later when you override values. Declaring on a component class limits the property to that component and its descendants.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Scope demo</title>
<style>
:root {
--gap: 8px;
}
.panel {
--panel-bg: #eef2ff;
background: var(--panel-bg);
padding: var(--gap);
}
.outside {
/* --panel-bg is not defined here */
background: var(--panel-bg, white);
padding: var(--gap);
}
</style>
</head>
<body>
<div class="panel">Uses --panel-bg and --gap.</div>
<div class="outside">Only --gap is available here.</div>
</body>
</html>The .outside element does not descend from .panel, so it never receives --panel-bg. The second argument to var() supplies a fallback so the rule still produces a usable background. The next-but-one section introduces that argument, and the chapter after the naming chapter covers fallbacks in full.
Consuming a property with var()
var(--name) is replaced by the value of that property on the same element. The substitution happens at computed-value time, after the cascade has picked the winning declaration for each property on each element. That timing explains most of the behavior in this chapter.
:root {
--radius: 6px;
--accent: #0f766e;
}
.button {
border-radius: var(--radius);
background: var(--accent);
color: white;
}You can use var() in two places:
- As the value of a standard property, or part of one.
- As part of the value of another custom property.
The second case lets you build tokens from other tokens:
:root {
--color-blue-500: #2563eb;
--color-accent: var(--color-blue-500);
}If a custom property refers to itself, directly or through a chain, every property in the cycle becomes invalid. The browser does not try to resolve it.
Using var() inside larger values
var() can stand in for any whole token or run of tokens, so you can combine it with other text in a value.
:root {
--border-width: 1px;
--color-border: #d1d5db;
--columns: 3;
--gap: 12px;
}
.card {
border: var(--border-width) solid var(--color-border);
margin: var(--gap) calc(var(--gap) * 2);
}
.grid {
display: grid;
grid-template-columns: repeat(var(--columns), 1fr);
gap: var(--gap);
}A value is substituted as tokens, not as a string. That difference creates one of the most common beginner errors.
:root {
--size: 16;
}
.broken {
width: var(--size)px; /* invalid: becomes "16 px" */
}
.fixed {
width: calc(var(--size) * 1px); /* 16px */
}In .broken, the substitution produces the two tokens 16 and px with nothing joining them, so the declaration is invalid. When a token is a bare number, multiply it by a unit inside calc(). Better still, store the unit in the token: --size: 16px.
Where var() does not work
The substitution only applies to property values. It does not work in selectors, in property names, or in media query conditions.
| Location | Example | Works? |
|---|---|---|
| Value of a standard property | `padding: var(--gap)` | Yes |
| Value of a custom property | `--a: var(--b)` | Yes |
| Argument inside `calc()` | `width: calc(var(--n) * 1px)` | Yes |
| Property name | `var(--prop): red` | No |
| Selector | `.var(--name) { }` | No |
| Media query condition | `@media (min-width: var(--bp))` | No |
Media queries are evaluated before any element exists, so there is no element for the browser to read a property from. If you need one breakpoint value in both CSS and JavaScript, keep it as source data and generate the literal value into your CSS. The last chapter of this tutorial covers that approach.
What happens when a value is invalid
A bad custom property value is accepted without complaint, so mistakes show up later, when a property tries to use it. If the substituted value is not valid for the property that uses it, that property is said to be invalid at computed-value time. The declaration is not skipped the way an invalid declaration normally is. The cascade has already chosen it, so the browser cannot go back to an earlier rule. The property instead behaves as if you had written unset.
:root {
--space: 1rem;
}
.a {
background: var(--space); /* not a valid background: initial value, transparent */
}
.b {
color: var(--space); /* not a valid color: color inherits, so parent's color */
}unset means inherit for properties that inherit by default (like color) and initial for the rest (like background). If an element suddenly loses a style and DevTools shows no error, check for this case. The pitfalls chapter covers it fully.
A custom property that is referenced but never declared behaves in a similar way. With no fallback, var(--missing) makes the whole declaration invalid at computed-value time.
How resolution fits together
The key point is the order. The cascade and inheritance run first, and the substitution happens afterward, element by element. This is why overriding --accent on a nested element changes everything inside that element that uses var(--accent), without touching any rule that reads the token.
Useful details
- Whitespace is trimmed. Leading and trailing whitespace around the value is not kept, though whitespace inside is. When you read a property from JavaScript you may still see a leading space from how the stylesheet was written, so the JavaScript chapter calls
trim(). !importantworks.--gap: 4px !important;wins the cascade for that property like any other declaration.- Global keywords work.
--gap: inherit;takes the parent's value.--gap: initial;resets the property to the guaranteed-invalid value, which acts as if it were never declared, so a fallback applies. - Shorthands are allowed. A property can hold a whole shorthand value such as a
box-shadowlist or a font stack, as the earlier examples show. Prefer the form that stays easiest to read at the point of use. - Custom properties do not affect rendering on their own. Declaring
--gapchanges nothing on the page until some standard property references it.
A worked example
This stylesheet puts the chapter's pieces together. It declares a few tokens on :root, builds one from another, and consumes them with var() inside shorthands and calc().
:root {
--color-text: #111827;
--color-surface: #f9fafb;
--color-accent: #2563eb;
--space-unit: 4px;
--radius: 6px;
--border: 1px solid #d1d5db;
}
body {
margin: 0;
color: var(--color-text);
background: var(--color-surface);
font-family: system-ui, sans-serif;
}
.card {
border: var(--border);
border-radius: var(--radius);
padding: calc(var(--space-unit) * 4);
margin-block: calc(var(--space-unit) * 3);
}
.card a {
color: var(--color-accent);
}To restyle this page you change values in one rule. To change spacing everywhere, edit --space-unit. Because no color or length is repeated in the rules below :root, a design change touches only the :root block.
Exercises
Exercise
A stylesheet contains :root { --size: 20; } and .box { width: var(--size)px; }. The box has no width. Why, and how do you fix it?
Show answer
Substitution works on tokens, so var(--size)px becomes 20 px, with the number and the unit as separate tokens. That is not a valid width, so the declaration is invalid at computed-value time. Fix it with width: calc(var(--size) * 1px);, or declare --size: 20px; and write width: var(--size);.
Exercise
You write --Accent: #0f766e; on :root and color: var(--accent); on a link. The link keeps its inherited color. Name the cause and one more place var() cannot be used.
Show answer
Custom property names are case-sensitive, so --Accent and --accent are different properties, and --accent is undefined. With no fallback, color becomes invalid at computed-value time and acts as unset, which means inherit for color. Another place var() does not work is a media query condition, such as @media (min-width: var(--bp)). It is also not allowed in selectors or property names.