var() CSS Function
Description
The var() CSS function is used to insert the value of a custom property (also known as a CSS variable) into other style rules. It allows you to define reusable values in one place and reference them throughout your stylesheet, which makes managing themes, colors, spacing, and other repeated values much easier. Custom properties themselves are declared using the --property-name syntax, and var() retrieves their value wherever needed.
One key feature of var() is that it can accept a fallback value, which will be used if the referenced custom property is not defined. This ensures that your styles remain robust and avoid unexpected invalid values.
For example, you can use var() with color or background-color like this:
:root {
--main-color: #3498db;
--secondary-color: #2ecc71;
}
button {
background-color: var(--main-color);
border: 2px solid var(--secondary-color, #000); /* fallback if --secondary-color is missing */
color: var(--text-color, white); /* fallback to white if --text-color is missing */
}
var() can also be used in combination with functions such as calc() for dynamic sizing:
:root {
--spacing: 16px;
}
.container {
padding: calc(var(--spacing) * 2);
}
This approach allows you to centralize control of key style values, making it easy to update themes or design tokens across an entire project without manually changing each instance.
Additionally, var() can be applied to virtually any CSS property that accepts a value, including font-size, margin, and width, making it a versatile tool in modern CSS development.
Syntax
var() = var( <custom-property-name> , <declaration-value>? )
Values
- <custom-property-name>A custom property's name represented by an identifier that starts with two dashes. Custom properties are solely for use by authors and users; CSS will never give them a meaning beyond what is presented here.
- <declaration-value>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.
Example
Browser Support
The following information will show you the current browser support for the CSS var() function. Hover over a browser icon to see the version that first introduced support for this CSS function.
This function is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 1st January 2026
