CSSadvanced 8 min
Reusable values with CSS variables, and how they make themes easy.
How to declare CSS variables, use them with var(), give them defaults, and change them for a whole section of a page.
Without variables, a brand colour is copied into dozens of rules. Changing it means hunting through the file. With a variable you change it once, and you can build themes such as light and dark easily.
A custom property (CSS variable) is a name starting with two dashes, defined like any property and used with var():
:root is the top of the document, so variables defined there are available everywhere.var(--name, fallback) uses a fallback value if the variable is missing.element.style.setProperty("--brand", "tomato").:root defines --brand (blue) and --radius..btn reads them with var()..warm redefines --brand as tomato. Any .btn inside it reads the new value, so the second button is red. The CSS of .btn did not change at all.Add a --text: white variable and use it for the button's color. Then override it inside .warm.
--brand, not -brand.body but using outside it, or defining on a child but using on a parent.--name: value; and read it with var(--name).:root, override locally to restyle sections.Next: keyframe animations.
:root {
--brand: royalblue;
--space: 16px;
}
button {
background: var(--brand);
padding: var(--space);
}<style>
:root {
--brand: royalblue;
--radius: 10px;
}
.btn {
background: var(--brand);
color: white;
border: none;
padding: 10px 18px;
border-radius: var(--radius);
}
.warm {
--brand: tomato;
}
</style>
<button class="btn">Default</button>
<div class="warm">
<button class="btn">Inside .warm</button>
</div>