CSS variables โ officially called custom properties โ let you store values and reuse them throughout your stylesheet. Change the variable in one place, and it updates everywhere. If you have ever used variables in any programming language, you already understand the concept.
Defining and Using Variables
You define a variable with two dashes -- and use it with var():
:root {
--primary-color: #3498db;
--text-color: #333;
--spacing: 20px;
}
body {
color: var(--text-color);
}
button {
background-color: var(--primary-color);
padding: var(--spacing);
}
The :root selector targets the HTML element, making these variables available
globally. Define them once, use them everywhere.
Scoping
CSS variables respect the cascade. If you define a variable inside a specific element, only that element and its children can use it.
.card {
--card-bg: #f9f9f9;
background-color: var(--card-bg);
}
.card-header {
background-color: var(--card-bg); /* works โ same scope */
}
This is useful for component-level theming. A card component can define its own variables without affecting anything else on the page.
Fallback Values
The var() function accepts a fallback value as the second argument. If the
variable is not defined, the fallback kicks in.
button {
background-color: var(--button-color, #3498db);
/* uses --button-color if defined, otherwise #3498db */
}
Fallbacks make your code more robust. Even if someone forgets to define the variable, your design does not break.
Dynamic Variables with JavaScript
One of the coolest things about CSS variables is that you can change them with JavaScript. This makes runtime theming incredibly easy.
document.documentElement.style.setProperty('--primary-color', '#e74c3c');
One line of JavaScript changes the primary color everywhere on the page. No need to hunt down every selector. This is how most dark mode toggles work.
Why Use CSS Variables?
Preprocessor variables (Sass, Less) are compiled at build time and cannot change afterward. CSS variables are live โ they update in real time. Combined with JavaScript, they open up possibilities like theme switching, user-customizable colors, and interactive design changes. They are one of the best additions to modern CSS.