In this article · 9 sections
Changing your brand colour across a website shouldn't mean editing 200 lines of CSS. CSS variables (officially "custom properties") let you define values once and reuse them everywhere. They're the foundation of modern theming, design systems and dark mode.
The basics
:root {
--brand: #1B6FD8;
--accent: #F5C400;
--text: #1a1f36;
--radius: 12px;
}
.btn {
background: var(--accent);
color: var(--text);
border-radius: var(--radius);
}
a { color: var(--brand); }
- Define variables with
--name: value; - Use them with
var(--name) :rootmakes them available everywhere
Fallback values
color: var(--link-color, #1B6FD8);
If --link-color isn't defined, the fallback is used.
Scoping and overrides
Variables follow the cascade, so you can override them for a section or component:
.card { --card-bg: #fff; background: var(--card-bg); }
.card.highlight { --card-bg: #fefbe8; }
.dark-section { --text: #e6e9f2; }
Build a spacing and type scale
:root {
--space-1: 4px; --space-2: 8px; --space-3: 16px; --space-4: 24px; --space-5: 48px;
--fs-body: 1rem; --fs-h2: clamp(1.5rem, 3vw, 2rem);
}
section { padding: var(--space-5) 0; }
See fluid typography with clamp() and design systems.
Dark mode in a few lines
:root { --bg: #ffffff; --text: #1a1f36; --surface: #f4f6fb; }
@media (prefers-color-scheme: dark) {
:root { --bg: #0f1420; --text: #e6e9f2; --surface: #172033; }
}
body { background: var(--bg); color: var(--text); }
Change variables with JavaScript
document.documentElement.style.setProperty('--brand', '#D42B2B');
Useful for theme switchers, user preferences or live previews in an admin panel.
Variables vs Sass variables
Sass variables are replaced at build time; CSS variables exist in the browser, so they can change at runtime, inherit, and respond to media queries. Many projects use both.
Tips
- Name by purpose (
--brand,--danger), not appearance (--blue) - Keep a short list of core tokens
- Document them at the top of your stylesheet
- Use them consistently; mixing hard-coded colours defeats the purpose
FAQs
Are CSS variables supported in all browsers?
Yes, in all modern browsers.
Do CSS variables affect performance?
Not noticeably for normal use. They make maintenance much easier.
Every Joboo Web site uses CSS variables for consistent, easy-to-update branding. Get in touch.