Say you want to change your site’s theme color from orange to green. The orange you wrote in color and background is in 30 spots all over the page — finding and rewriting them all is hard work. There’s a way to give a color a name and manage it in one place. That’s CSS variables.
The way to write it: “stash” and “take out”
:root {
--main-color: #ff8a3d;
}
h2 {
color: var(--main-color);
}
.button {
background: var(--main-color);
}| Part | Meaning |
|---|---|
:root | A special selector pointing to the whole page (the go-to place to stash variables) |
--main-color | The variable’s name. Start it with -- and name it whatever you like |
var( ) | The container that takes out the stashed value |
The h2’s text and the .button’s background are, at heart, the same --main-color. Change that one line in :root to #2ec46f and both turn green at once.
Let’s see it in action
The heading color, the button, the badge — a mini page where everything is written with var(--main-color). The button switches just the contents of the variable.
--main-color. The underline, the badge, and the button are all written with var(--main-color), so a change in one place reaches the whole page.You can also override it in parts
CSS variables can be defined not only in :root but inside any selector you like. They have the property that the value is overridden only inside the place where you defined it.
:root {
--main-color: #ff8a3d;
}
.dark-card {
--main-color: #2ec46f;
}var(--main-color) becomes #2ec46f only inside parts with the .dark-card class, while the rest of the page stays #ff8a3d as usual. It’s a handy property for when you want to change the color only there.
You can stash more than colors
It’s not only colors you can stash in a variable. Spacing, font sizes, and other values you use repeatedly — you can stash anything.
:root {
--main-color: #ff8a3d;
--content-width: 800px;
--card-radius: 12px;
}Picture a “settings table for the whole site” forming at the top of your CSS. It’s a kind way to write for the future you who looks back at it too.
TipsColor-scheme sites so you never agonize over colorIf you’re unsure which theme color to choose in the first place, see our roundup of color-scheme sitesSummary of this lesson
- Stash with
--name: value;inside:root, and take out withvar(--name) - Reuse the same color with
var(), and one change reaches the whole page - Not just colors — you can stash any values you use repeatedly, like spacing and widths