Loading lessons...
CSS Variables
CSS Variables (custom properties)
Store values once, reuse everywhere. Change one = updated site-wide!
Define them
Variables are custom properties starting with --. Set them on any element (often :root):
:root {
--brand: #04aa6d;
--spacing: 8px;
}
Use with var():
.btn {
background: var(--brand);
padding: calc(var(--spacing) * 2);
}
Scope
Variables inherit like other CSS values:
- On
:root, global. - On a modal/box, only inside it.
.card {
--card-bg: white;
}
.special {
--card-bg: gold; /* overrides in this subtree */
}
fallbacks
var(--custom, fallback):
p {
color: var(--text-color, black);
}
With Media Queries (bonus!)
@media (max-width: 600px) {
:root {
--title-size: 2rem;
}
}
Define a var once, then adjust it in the query. Clean theming!
References everywhere
Vars can hold any value: colors, sizes, gradients, running-clip paths... even other var() references.
TL;DR
--namedefines a custom property.var(--name)reads it.- Scope on :root (global) or any element subtree.
- Fallback: var(--x, default).
- Perfect for themes: change once, apply zone-wide.
- Interactive via media queries & JS.