Introduction to CSS Variables
CSS variables (also called custom properties) let you reuse values in your styles. Learn what they are and how to use them with simple examples.
What Are CSS Variables?
CSS variables are variables you can use directly in your CSS code. Also known as CSS Custom Properties, they bring the familiar concept of variables from programming languages like JavaScript and PHP into CSS. By introducing CSS variables, you can now enjoy the benefits of using variables—such as reusability and easier maintenance—within your stylesheets.
Web developers widely use CSS variables because they make CSS code more reusable and easier to maintain. In this guide, we'll first explore why CSS variables are necessary, then cover how to use them effectively, and finally, how to change their values dynamically.
Why Use CSS Variables?
Variables are tools for storing and reusing values, widely used in programming languages like JavaScript and PHP.
By introducing variables in CSS, you can now take advantage of their benefits in your stylesheets as well.
Using variables is especially helpful when you need to use the same value multiple times.
For example, suppose your website’s primary color is a deep purple (#8B008B
).
To set the text color to this deep purple, you could write the following CSS code:
p {
color: #8B008B;
}
However, if you need to use this deep purple color multiple times throughout your website, you would have to repeat similar CSS code again and again:
p {
color: #8B008B;
}
h1 {
background-color: #8B008B;
}
div {
border-color: #8B008B;
}
/* ... */
In this case, you end up inserting the color code #8B008B repeatedly in your styles.
Now, what if you decide to change the primary color from deep purple to a dark gray (#A9A9A9
), perhaps due to a design update or policy change?
How would you update your code?
Of course, you could manually change each occurrence like this:
p {
color: #A9A9A9;
}
h1 {
background-color: #A9A9A9;
}
div {
border-color: #A9A9A9;
}
/* ... */
But what if there are not just a few, but hundreds of places where you need to change this color code?
While you could use an editor’s find-and-replace feature to update all instances at once, such repetitive manual edits can be tedious and prone to errors. Additionally, as shown in the example above, it can be difficult for the human eye to spot and distinguish color codes scattered throughout the code.
The following example demonstrates how to use CSS variables to set the primary color of a website to deep purple. Even if you’re not familiar with CSS variables yet, you should be able to get the general idea by looking at the code.
/* Example using CSS variables */
:root {
--primary-color: #8B008B;
/* Store the website’s primary color, deep purple (#8B008B), in a variable named --primary-color */
}
p {
color: var(--primary-color);
/* Use var(variable-name) to insert the value of --primary-color where needed */
}
h1 {
background-color: var(--primary-color);
}
div {
border-color: var(--primary-color);
}
/* ... */
Now, let’s say you want to change the website’s primary color from deep purple to dark gray (#A9A9A9
) due to a design update or policy change.
/* Example using CSS variables */
:root {
--primary-color: #A9A9A9; /* Changed from purple (#8B008B) to dark gray (#A9A9A9) */
}
p {
color: var(--primary-color);
}
h1 {
background-color: var(--primary-color);
}
div {
border-color: var(--primary-color);
}
/* ... */
As you can see from this example, compared to not using CSS variables, CSS variables allow you to update the value in one place only — changing --primary-color: #8B008B
to --primary-color: #A9A9A9
— making it much easier and more convenient to reuse and maintain your CSS code.
CSS variables are a powerful feature that helps you write reusable and maintainable CSS.
Wait a minute!
CSS variables, also known as custom properties, were introduced in 2015 and officially standardized in 2017 as part of CSS Cascading and Inheritance Level 3.
In the next section, we’ll explore how CSS variables work and how to use them effectively.
CSS Variables in Action: Syntax and Usage Examples
CSS variables (also known as custom properties) are defined using a specific syntax and can be used within the scope of the selector where they are declared.
Defining a CSS Variable
selector {
--primary-color: #8B008B;
/* Syntax: --variable-name: value; */
}
selector
: Determines where the variable is available.
To make the variable available globally, use:root
orbody
.
To limit the scope to a specific element and its descendants (e.g.,.container
), use that selector.--primary-color
: This is the variable name.
All custom property names must begin with two dashes (--
).#8B008B
: This is the value assigned to the variable.
Once a variable is defined, you can use it in any descendant of the selector by calling it with the var()
function. For example, var(--primary-color)
is equivalent to #8B008B
.
Using a CSS Variable
p {
color: var(--primary-color); /* Equivalent to color: #8B008B; */
}
h1 {
background-color: var(--primary-color); /* Equivalent to background-color: #8B008B; */
}
div {
border-color: var(--primary-color); /* Equivalent to border-color: #8B008B; */
}
In this example, the variable --primary-color
is used inside elements that are within the scope of the selector where it was originally defined.
If the variable was defined in :root
, it will be accessible throughout the entire document.
Understanding Variable Scope in CSS
In CSS, the scope of a custom property (CSS variable) depends on where it is defined. A variable is only available to the element it’s defined on and all of its descendants.
Global Scope with :root
To make a variable available throughout your entire stylesheet, define it on the :root selector. This is a special selector that targets the root element of the document (usually the <html>
element).
For example:
:root {
--main-bg-color: #f0f0f0;
}
body {
background-color: var(--main-bg-color);
}
header {
background-color: var(--main-bg-color);
}
In this example, --main-bg-color
is globally available because it is defined on :root
.
Local Scope with a Specific Selector
You can also define a variable inside a specific element’s scope. In this case, the variable is only available to that element and its children.
For example:
.container {
--highlight-color: yellow;
}
.container p {
background-color: var(--highlight-color); /* Works */
}
.sidebar p {
background-color: var(--highlight-color); /* Won’t work */
}
Here, --highlight-color
is defined on .container
, so it can only be used inside .container
and its descendants. It is not available in .sidebar
or elsewhere outside .container
.
Note:
Always define global variables in :root
if you plan to reuse them in multiple parts of your stylesheet.
Inheritance and Overriding of CSS Variables
CSS variables are inheritable, meaning that if a custom property is not explicitly defined on an element, it inherits the value from its parent element. Let’s examine the following HTML example:
<div class="one">
one
<div class="two">
two
<div class="three">three</div>
<div class="four">four</div>
</div>
</div>
The following CSS will be applied:
.two {
--test: 10px;
}
.three {
--test: 2em;
}
div {
font-size: var(--test);
}
The computed font-size: var(--test)
values will be:
- Elements with class
.two
have a font size of 10px. - Elements with class
.three
have a font size of 2em. - Elements with class
.four
inherit the font size 10px from their parent.two
. - Elements with class
.one
have no valid font size from the variable (since--test
is not defined or inherited).
As shown in this example, CSS variables are inherited only within the scope of the selector where they are defined. When you override a variable value within its scope, the changed value is inherited by that selector’s descendants.
Changing CSS Variable Values in Responsive Design (Media Queries)
You can also change the value of CSS variables within media queries to implement responsive web design.
:root {
--font-size: 15px;
}
p {
font-size: var(--font-size);
}
@media (max-width: 1024px) {
:root {
--font-size: 13px;
}
}
In the example above, when the viewport width is 1024px or less, the<p>
element’s font size becomes 13px. This demonstrates how CSS variable values can be updated within media queries.
Using Fallback Values for CSS Variables
A fallback value in a CSS variable is an optional default value that gets used when the variable is not defined. This ensures that your styles remain intact, even if a particular variable hasn’t been set.
Fallback values are provided as the second argument of the var()
function. Here's the syntax:
/* Syntax of the var() function */
var(--variable-name[, fallback-value]);
The fallback value is used only if the specified variable has not been defined. Let’s look at an example of how to use fallback values in CSS:
:root {
--primary-color: #00a0e9;
}
.container {
color: var(--primary-color, #1a1aff);
background-color: var(--secondary-color, #3333ff); /* --secondary-color is not defined */
}
In the example above, the color
property in .container
uses var(--primary-color, #1a1aff)
. Since --primary-color
is defined in the :root
, its value #00a0e9
is applied.
However, the background-color
uses var(--secondary-color, #3333ff)
, and --secondary-color
is not defined. In this case, the fallback value #3333ff
is used instead.
Using fallback values helps maintain the visual integrity of your page and prevents unexpected rendering errors.
Using Another Variable as a Fallback
You can also use another CSS variable as a fallback. Here's a valid example:
.container {
background-color: var(--my-var, var(--my-background, pink));
/* If --my-var and --my-background are both undefined, 'pink' will be used */
}
Be careful not to use multiple variables as a single argument like this:
.container {
background-color: var(--my-var, --my-background, pink);
/* Invalid: "--my-background, pink" is treated as a single argument */
}
Also, using another variable as a fallback only works if that fallback is itself defined or includes a valid fallback:
.container {
background-color: var(--my-var, --my-primary-background);
/* Invalid: --my-primary-background is used as a fallback, but it’s not a valid fallback on its own */
}
CSS fallback values offer a powerful way to build resilient and maintainable styles. By properly using the second argument of the var()
function, you can avoid broken layouts and make your stylesheets more robust.
Browser compatibility
Attribute |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
--*
|
49 | 15 | 31 | 9.1 |
var()
|
49 | 15 | 31 | 9.1 |
Specifications
Specification | |
---|---|
CSS Variables
|
CSS Custom Properties for Cascading Variables Module Level 1 #defining-variables |