How to use CSS variables for colors
Short answer
Declare the colors once in :root and use them with var():
<style>
:root { --brand: royalblue; --text: #222; --surface: aliceblue; }
.card { padding: 12px; background: var(--surface); color: var(--text); border-left: 4px solid var(--brand); }
.card a { color: var(--brand); }
</style>
<div class="card">Our new plan is out. <a href="https://example.com">See prices</a></div>A variable name starts with two hyphens. Change --brand and the color changes everywhere it is used.
Overriding for a block
Variables are inherited, so you can override them inside a single block:
<style>
:root { --brand: royalblue; }
.btn { padding: 6px 14px; border: none; background: var(--brand); color: white; }
.danger { --brand: crimson; }
</style>
<button class="btn">Save</button>
<div class="danger"><button class="btn">Delete</button></div>A fallback and shades
The second argument of var() is used when the variable is not set. And color-mix() makes a light shade from the main color without a new variable:
.note { background: color-mix(in oklch, var(--brand, teal) 15%, white); }Common mistake
People write color: --brand or color: $brand — neither works. A variable's value is read only with var(--brand). Another trap is case: --Brand and --brand are two different variables.
Functions used in this recipe
- var() — Inserts the value of a custom property (a CSS variable).
- :root — Matches the root element of the document — `<html>` on a web page.
- color-mix() — Mixes two colors in the given proportion.