Sub topic 1
Declaring custom properties and reading them with var()
CSS custom properties are values you define yourself and reuse across a stylesheet. This chapter covers how to declare them, how to read them with var(), and the rules that govern their names and values. Later chapters cover fallbacks, scope, theming, and @property in more detail.
Prerequisites
This chapter assumes you already know:
- Basic CSS syntax: selectors, properties, and values.
- The cascade and specificity at a working level. You know that a more specific selector beats a less specific one, and that a later rule beats an earlier one of equal specificity.
- Basic HTML structure: elements, classes, and attributes.
You do not need JavaScript for this chapter. JavaScript access to custom properties has its own chapter.
What a custom property is
A custom property is a property whose name you choose. The name must begin with two dashes (--). Unlike built-in properties such as color or padding, the browser attaches no meaning to it. It stores a value, and you decide where that value is used.
Custom properties are often called "CSS variables". The name is reasonable, but they differ from variables in a programming language. They take part in the cascade and they inherit. Their value can differ from one element to the next. The browser resolves them while computing styles, not when it parses the file.
Declaring a custom property
You declare a custom property the same way you declare any property: a name, a colon, a value, and a semicolon. It must appear inside a rule block.
:root {
--brand-color: #0b5fff;
--space: 8px;
}:root matches the document's root element, which is <html> in an HTML page. Declaring properties there makes them available to every element on the page, because custom properties inherit. This is the usual place for values shared across the whole site. Other scopes are covered in a later chapter.
Naming rules
- The name starts with
--. After that you can use letters, digits, hyphens, and underscores. Most other characters are also allowed if you escape them, but you rarely need to. - Names are case-sensitive.
--Brand-Colorand--brand-colorare different properties. Built-in properties are not case-sensitive in this way, so this catches people out. --alone is reserved by the CSS specification and should not be used as a name.
Pick lowercase names with hyphens, and name them for their purpose, not their value. --brand-color will still make sense after a rebrand. --blue will not.
What a value can contain
A custom property accepts almost any sequence of tokens. The browser does not check it against a type when you declare it. All of these are valid declarations:
:root {
--size: 16px;
--font-stack: "Inter", system-ui, sans-serif;
--shadow: 0 2px 4px rgb(0 0 0 / 0.2);
--empty:;
--ratio: 16 / 9;
--label: "Save";
}Some points about these values:
- Whitespace is preserved in the stored value, though leading and trailing whitespace is trimmed. This matters when you read the value back from JavaScript.
- A value may be a fragment that is not valid on its own.
--shadowabove is not a complete declaration. It only becomes meaningful when you substitute it into a property such asbox-shadow. - An empty value, as in
--empty:;, is valid. Its substitution produces nothing. Do not confuse it with an unset property. - Braces and brackets must balance, and a bare
;or an unmatched}ends the value or breaks it.
Because the browser does not validate custom property values at declaration time, a typo such as --size: 16xp; is accepted without complaint. The problem appears later, when you use the value. Chapter four covers that failure mode.
Reading a value with var()
The var() function reads a custom property and substitutes its value in place.
.button {
background: var(--brand-color);
padding: calc(var(--space) * 2);
}With the declarations from earlier, the browser sees background: #0b5fff and padding: calc(8px * 2). The second case shows that var() can sit inside other functions. The substitution happens first, and then calc() evaluates the result.
You can use var() in the value of almost any built-in property. You can also use it in the value of another custom property, which lets you build values from other values:
:root {
--brand-color: #0b5fff;
--link-color: var(--brand-color);
}Where var() cannot be used
var() can only appear in a property value. It cannot be used:
- As a property name.
var(--prop): red;is invalid. - In a selector.
.var(--name) { }is invalid. - In a media query condition.
@media (min-width: var(--bp))does not work. Later chapters return to this limitation. - To build a partial token.
var(--n)pxdoes not turn--n: 10into10px. The result is10 px, which is invalid. Usecalc(var(--n) * 1px)instead.
The last case is a common source of bugs. Substitution works on whole tokens, not on text.
:root {
--n: 10;
}
.box {
/* Invalid: becomes "10 px" */
width: var(--n)px;
/* Valid: 10 * 1px = 10px */
width: calc(var(--n) * 1px);
}How the browser handles the declaration
Custom properties are processed in three steps, and knowing them helps when you debug.
- Parse. The browser stores the declared tokens as the property's specified value. Aside from checking that braces balance, it does not validate them.
- Cascade and inherit. The browser picks the winning declaration for each element, using the normal rules of origin, specificity, and order. If no declaration applies, the element inherits the parent's value.
- Substitute. For every built-in property that contains
var(), the browser replaces eachvar()with the custom property's value. It then checks whether the result is valid for that built-in property.
The key consequence is that validation happens at step three, in the context of the property that uses the value. The same custom property can be valid in margin and invalid in color.
:root {
--space: 8px;
}
.a {
margin: var(--space); /* valid: margin: 8px */
color: var(--space); /* invalid for color */
}When the result is invalid, the declaration does not fall back to an earlier rule in the cascade. The property is treated as if it were unset, which means it takes its inherited value or its initial value. This is the "invalid at computed-value time" behavior. It is the main difference from an ordinary invalid declaration, which the browser discards at parse time so that an earlier valid declaration still applies. A later chapter covers it fully.
A complete example
The following page uses custom properties for a small spacing scale and a brand color. The values are declared once and used in several rules.
:root {
--brand-color: #0b5fff;
--text-color: #1a1a1a;
--space: 8px;
--radius: 4px;
}
body {
color: var(--text-color);
margin: 0;
padding: calc(var(--space) * 3);
font-family: system-ui, sans-serif;
}
.button {
background: var(--brand-color);
color: white;
border: 0;
border-radius: var(--radius);
padding: var(--space) calc(var(--space) * 2);
}
.card {
border: 1px solid var(--brand-color);
border-radius: var(--radius);
padding: calc(var(--space) * 2);
}To change the brand color or the base spacing, you edit one line in :root. Every rule that reads the property updates with it. If you used plain values, you would have to find and edit each occurrence.
Comparing with preprocessor variables
If you have used Sass or Less, you may wonder how custom properties differ from $variable syntax. The table summarizes the points that matter in daily work.
| Aspect | Sass or Less variable | CSS custom property |
|---|---|---|
| Resolved | At build time, before the browser sees the CSS | In the browser, while computing styles |
| Follows the cascade | No | Yes |
| Inherits through the DOM | No | Yes |
| Can change at runtime | No | Yes, through CSS rules or JavaScript |
| Can be used in a media query condition | Yes | No |
| Needs a build step | Yes | No |
Neither one replaces the other. A preprocessor variable suits values needed only at build time. A custom property suits values that change with context or at runtime.
Common mistakes
- Forgetting the dashes.
brand-color: blue;declares nothing useful. The browser discards it as an unknown property. - Declaring outside a rule. A bare
--x: 1px;at the top level of a stylesheet is ignored. It must be inside a block. - Wrong case.
var(--Brand-Color)does not find--brand-color. - Using var() for part of a unit. As shown above, use
calc()with a multiplication. - Expecting an error for a bad value. The browser accepts any token sequence at declaration. Open DevTools and inspect the computed value to find the problem.
Summary of key points
- A custom property name begins with
--and is case-sensitive. - It must be declared inside a rule block.
:rootis the common location for site-wide values. - Its value is stored as raw tokens and is not validated until a
var()substitutes it into a built-in property. var()works inside property values and inside other functions such ascalc(). It does not work in selectors, property names, or media query conditions.- Substitution replaces whole tokens. Use
calc(var(--n) * 1px)to attach a unit to a bare number.
Exercise
A stylesheet declares :root { --gap: 12; } and a rule .row { margin-top: var(--gap)px; }. The margin has no effect. Explain why, and rewrite the rule so the margin is 12 pixels.
Show answer
var() substitutes whole tokens, so var(--gap)px becomes 12 px, with a space between the number and the unit. That is not a valid length, so the declaration is invalid at computed-value time and margin-top takes its initial value. Rewrite it as .row { margin-top: calc(var(--gap) * 1px); }. The multiplication produces 12px.
Exercise
You write --Accent: tomato; in :root and later use color: var(--accent);. The text color does not change. What is the cause, and what are two ways to fix it?
Show answer
Custom property names are case-sensitive, so --Accent and --accent are different properties and var(--accent) finds nothing. Fix it by renaming the declaration to --accent, or by changing the usage to var(--Accent). The first option is better because lowercase names are the common convention.
Exercise
Why can --size: 16xp; be declared without any error, and at what point does the problem show up?
Show answer
The browser does not check a custom property's value against a type when it is declared. It stores the tokens as written. The problem appears at substitution time. When width: var(--size) is computed, the result 16xp is not a valid width, so the declaration is invalid at computed-value time and width takes its inherited or initial value.