CSS var() Function
Example
:root {
--bg-color: red;
}
p {
background: var(--bg-color);
}
Meaning
The var() css function specifies the value of a custom property (CSS variable) instead of any part of a value of another property.
The var() function cannot be used in property names, selectors or anything else besides property values.
Version: CSS3
Standard Syntax
var(--customPropertyName, declarationValue)
The first argument to the function is the name of the custom property to be substituted. An optional second argument to the function serves as a fallback value. If the custom property referenced by the first argument is invalid, the function uses the second value.
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Status
Function Arguments
The following table describes the arguments of this function.
Argument | Description |
---|---|
--customPropertyName | Required. Specifies the identifier that starts with two dashes. |
declarationValue | Optional. The custom property's fallback value, which is used in case the custom property is invalid in the used context. This value may contain any character except some characters with special meaning like newlines, unmatched closing brackets, i.e. ), ], or }, top-level semicolons, or exclamation marks. The fallback value can itself be a custom property using the var() syntax. |
More Examples
--bg-color color isn't set, it will fall back to green.
Example
p {
background: var(--bg-color, green));
}
--bg-color1 and --bg-color2 color isn't set, it will fall back to green.
Example
p {
background: var(--bg-color1, var(--bg-color2, green));
}