The var()
function allows you to insert the value of a CSS variable into your styles.
CSS variables can be scoped locally or globally, giving them access to the DOM. This allows you to modify these variables dynamically using JavaScript or adjust them based on media queries.
Advantages
Using CSS variables for colors in your design is particularly beneficial. Instead of repeatedly copying and pasting the same color values, you can define them once in variables, making your code more maintainable and consistent.
The var() Function
The var()
function is used to insert the value of a CSS variable.
The syntax for the var()
function is as follows:
var(--name, value)
Note:Variable names must start with two dashes (--) and are case sensitive!
How var() Works
CSS variables can have either a global or local scope.
Global variables are accessible throughout the entire document, while local variables are limited to the specific selector in which they are defined.
To create a global variable, declare it within the :root
selector, which corresponds to the document’s root element.
To create a local variable, define it within the specific selector that will use it.
In the following example, we demonstrate how to use the var()
function.
First, we declare two global variables (--red
and --green
) inside the :root
selector. Then, we utilize the var()
function to apply the values of these variables later in the stylesheet.
:root {
--red: red;
--green: green;
}
h1 {
color: var(--red);
border-bottom: 5px solid var(--green);
padding-bottom: 10px;
}
p {
color: var(--red);
}
Override Global With Local
Sometimes, we may want variables to change only within a specific section of the page.
For instance, if we want a different shade of green for p
element, we can redefine the --green
variable within the p
selector. When var(--green
) is used inside this selector, it will apply the locally defined --green
value.
In this case, the local --green
variable will take precedence over the global --green
variable for the p
element.
:root {
--red: red;
--green: green;
}
h1 {
color: var(--red);
border-bottom: 5px solid var(--green);
padding-bottom: 10px;
}
p {
--green: lightgreen; /* local variable will override global */
color: var(--green);
}