CSS custom properties (variables)
- type
- declaration + function pair
- applies to
- any element it's defined on, and its descendants (it inherits)
- inherits
- yes
- common values
- --brand-color: #2563eb; used as var(--brand-color)
Where it goes
Defined inside a rule. :root (which means the whole page) is the usual spot for one the whole site uses. Used anywhere a normal value would go, inside var().
Example
:root {
--brand-color: #2563eb;
}
button {
background: var(--brand-color);
}
a {
color: var(--brand-color);
}Common mistakes
- Defining it in a narrow rule like .card and then using it outside the card. A custom property is only visible to the tag it is defined on and the tags inside that one.
- Forgetting the -- at the front. custom-color: blue; is just an unknown property the browser ignores.