What are CSS variables?
Last updated on 4 August 2025This article is a beginner-friendly introduction to an advanced CSS concept called CSS variables. They make your CSS cleaner and easier to maintain. This article will focus on the following four topics:
- Declaring a CSS variable.
- Using a CSS variable.
- Global and local scopes of CSS variables.
- Overriding a global CSS variable with a local CSS variable.
Declaring a CSS variable
To declare a CSS variable, use --
followed by a variable name inside a CSS selector.
selector {
--background-light: #FAFAFA;
}
In the above code, background-light
is the variable name,--background-light
is the CSS variable, and #FAFAFA
is the value assigned to the CSS variable.
Note: CSS variables are case-sensitive. This means --background-light
and --Background-light
are two different CSS variables.
Using a CSS variable
To use the above declared CSS variable, --background-light
, insert it inside the var()
function of a CSS selector.
body {
background-color: var(--background-light);
}
In the above code, the background-color
property of the body element takes the value of --background-light
variable using the var()
function. In simpler terms, the background color of the body element will be set to #FAFAFA
.
Global and local scopes of CSS variables
A global CSS variable is declared inside the :root
pseudo-selector and can be used throughout the stylesheet document. A local CSS variable is declared inside a particular CSS selector and can be used only inside that selector.
The following code demonstrates the declaration of the global variable, --background-light
, inside the :root
pseudo-selector. It is then used inside the body
selector
/* Declaring a global CSS variable */
:root {
--background-light: #FAFAFA;
}
/* Using the global CSS variable */
body {
background-color: var(--background-light);
}
The following example demonstrates the declaration and usage of the local variable, --background-light
/* Declaring and using a local CSS variable */
body {
--background-light: #FAFAFA;
background-color: var(--background-light);
}
Overriding a global CSS variable with a local CSS variable
Override a global CSS variable with a local CSS variable by re-declaring the CSS variable within a specific selector you want modified.
The following example demonstrates the overriding of a global CSS variable --background-light
inside the button
selector
:root {
--background-light: #FAFAFA;
}
body {
background-color: var(--background-light);
}
button {
--background-light: #D5D5D5; /* local CSS variable overrides global CSS variable */
background-color: var(--background-light);
color: #141414;
padding: 1rem;
}
Go beyond the basics
The following links are some excellent resources to learn more about CSS variables.