CSS Reference ยท Functions
The var() function
Reference for the CSS var() function: reading custom properties, fallback values, nesting, invalid-at-computed-time behavior, with live theming examples.
The var() function inserts the value of a custom property (a name starting with --) into another property. Custom properties inherit, so a value set on :root or on a component is available to everything below it, and can be overridden for just one subtree.
CSS
:root { --brand: #6366f1; } .button { background: var(--brand); padding: var(--pad, 0.75rem); }
Try it
Syntax
CSS
var( <custom-property-name> , <fallback>? ) color: var(--text); color: var(--text, #222); color: var(--text, var(--base-text, black));
Syntax and arguments
| Part | Description |
|---|---|
--name |
The custom property to read. Names are case-sensitive. |
fallback |
Optional. Used if the custom property is not defined (or holds the guaranteed-invalid value). Everything after the first comma is the fallback, including more commas. It may itself contain var(). |
Usage notes
- Substitution happens at computed-value time. The value is pasted in as tokens, then the property is parsed. If the result is invalid for that property, the property becomes invalid at computed-value time: it acts like
unset(inherited properties inherit, others take their initial value). It does not fall back to an earlier declaration in the cascade. - The fallback is only for a missing variable, not for an invalid value.
var(--size, 10px)with--size: bananadoes not use10px. - Where it works: in any property value, in other custom properties, and inside
calc(),clamp()and similar. It cannot be used in property names, selectors or media query conditions. (Container query and media conditions cannot read--vars.) - Scoping: a custom property is inherited like
color. Set defaults on:rootand override on a component or state class. - Registered properties: with
@propertya custom property gets a type, an initial value and can be animated. - Spaces and commas: custom properties can hold partial values like
10px 20px;var()pastes them exactly. - JavaScript:
el.style.setProperty('--brand', 'tomato')updates all consumers at once. - Cycles: a custom property that refers to itself (directly or indirectly) is invalid.
Browser support
Supported in every current browser.