CSS Custom Properties, calc() and Design Tokens: Variables for Colors, Spacing and Easy Theming
Declare and Use a Variable
css
:root {
--brand: #0b5fff;
--space: 1rem;
--radius: .5rem;
}
.btn {
background: var(--brand);
padding: var(--space) calc(var(--space) * 2);
border-radius: var(--radius);
}
Measured in Chrome
padding-top of an element using calc(var(--gap) * 2) with --gap: 12px is 24px
- Names start with two dashes
:rootis the top of the page, so variables there work everywhere- Use
var(--name)to read it calc()can do math with different units
Fallbacks
css
.card { color: var(--card-text, #222); } /* uses #222 if --card-text is not set */
Scope: Change a Variable in One Place
css
:root { --bg: #fff; --text: #1a1a1a; }
.dark-section { --bg: #10151f; --text: #f1f4f9; }
.section { background: var(--bg); color: var(--text); }
Variables follow inheritance. Inside .dark-section the same .section rule gets different colors, with no extra code.
A Small Token System
css
:root {
/* colors */
--color-bg: #ffffff;
--color-text: #1a1a1a;
--color-brand: #0b5fff;
--color-muted: #5b6577;
/* spacing scale */
--s-1: .25rem; --s-2: .5rem; --s-3: 1rem; --s-4: 2rem;
/* type */
--font-body: system-ui, sans-serif;
}
body { background: var(--color-bg); color: var(--color-text); font-family: var(--font-body); }
Theme Switching
css
:root { --color-bg: #fff; --color-text: #1a1a1a; }
@media (prefers-color-scheme: dark) {
:root { --color-bg: #10151f; --color-text: #f1f4f9; }
}
[data-theme="dark"] { --color-bg: #10151f; --color-text: #f1f4f9; }
javascript
const root = document.documentElement;
document.querySelector("#theme").addEventListener("click", () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
});
Change One From JavaScript
javascript
document.documentElement.style.setProperty("--brand", "#7b2ff7");
Check contrast After you change theme colors, test text contrast again. A good color on white may be hard to read on dark.
calc spacing Write spaces around
+ and - in calc(). calc(1rem+2px) is invalid.
Practice
- Make a page with brand color, spacing and radius variables
- Add a dark theme with
prefers-color-scheme - Add a button that toggles a
data-themeattribute
Conclusion
CSS variables hold reusable values with fallbacks and scope. They make themes and consistent design easy.
Quick Summary: Declare; fallback; scope; tokens; themes; JavaScript.

