CSS var() Function
The CSS var()
function is used for inserting a custom CSS property.
A custom property can be thought of as a variable. Custom properties allow you to define a style in one place, then reuse that style elsewhere in your style sheets, simply by using the name of the custom property.
Syntax
Here's the official syntax for the var()
function:
Explanation of the values below.
- <custom-property-name>
-
This is the name of the custom property you want to use.
Custom properties start with two hyphen characters (U+002D HYPHEN-MINUS). For example, a custom property could be called
--main-color
. You could then refer to that custom property by passing that value to thevar()
function.Also note that custom property names are case-sensitive (unlike other CSS properties). Therefore,
--main-color
and--Main-Color
are two different properties. - <declaration-value>
This optional argument is a fallback value, which is used as the substitution value when the referenced custom property is invalid.
Fallback Values
As indicated in the syntax, you can optionally provide a fallback value to be used in case the custom property is invalid.
Here's an example of using a fallback value.
In this case, the custom properties weren't even defined, so the var()
function used the fallback values.
Case-Sensitivity
It's important to remember that custom properties are case-sensitive. This is in contrast to regular CSS properties, which are case-insensitive.
Here's an example that demonstrates this.
This is exactly the same as the first example above, except that I'm now using the wrong case when referencing the custom properties.
Because of this, the var()
function has no effect.
However, if I used a fallback value, then the fallback value would be used.
CSS Specifications
The var()
function is defined in CSS Custom Properties for Cascading Variables Module Level 1 (W3C Candidate Recommendation, 03 December 2015)