CSS Variables
CSS custom properties — usually called variables — let you store a value once and reuse it everywhere. They live in the cascade, so they can be re-themed at runtime.
Defining and using
CSS
:root {
--brand: #04AA6D;
--radius: 6px;
--spacing: 1rem;
}
.button {
background: var(--brand);
border-radius: var(--radius);
padding: calc(var(--spacing) / 2) var(--spacing);
}
The convention is to declare global variables on :root (the <html> element). Any descendant can read them with var(--name).
Why use them
| Benefit | What it lets you do |
|---|---|
| DRY | Change one declaration instead of fifty. |
| Theming | Toggle dark mode by overriding the variables, not the components. |
| Runtime | JavaScript can read & write them — animate hue, contrast, scale. |
| Scoping | Re-declare a variable on a parent to retheme just that subtree. |
| Fallbacks | var(--brand, #04AA6D) uses the second value if the variable isn't set. |
Dark mode in five lines
CSS
:root { --bg: #fff; --fg: #111; }
[data-theme="dark"] { --bg: #111; --fg: #eee; }
body { background: var(--bg); color: var(--fg); }
Tip: Variables and specificity are independent —
var() resolves before the cascade picks a winning rule. That's what makes per-component theming so clean.Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Variables</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Use the brand custom property as the background.
.btn { background:
(--brand); }
A three-letter CSS function.
Discussion
Loading…