Why CSS Variables Are Still Underrated
We live in an era of utility classes and CSS-in-JS. It's easy to get caught up in Tailwind classes or styled-component templates. But beneath whatever abstraction you're using, native CSS variables (Custom Properties) remain one of the most powerful and underutilized features of modern web development.
When I started building design systems, I’d see components littered with hardcoded values:
.card {
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
padding: 24px;
}This works fine until you need a dark mode, or marketing decides the primary button should have more rounded corners, or you realize your padding is entirely inconsistent across the app.
The Shift to Tokens
Instead of values, think in tokens. A token is a named variable that represents a design decision.
:root {
/* Primitives (The palette) */
--color-slate-900: #0f172a;
--color-white: #ffffff;
--spacing-4: 16px;
--spacing-6: 24px;
--radius-md: 8px;
/* Semantics (The meaning) */
--bg-surface: var(--color-white);
--text-primary: var(--color-slate-900);
--p-card: var(--spacing-6);
--rounded-card: var(--radius-md);
}
@media (prefers-color-scheme: dark) {
:root {
--bg-surface: var(--color-slate-900);
--text-primary: var(--color-white);
}
}Now, your component becomes incredibly dumb (which is what you want!):
.card {
background-color: var(--bg-surface);
color: var(--text-primary);
border-radius: var(--rounded-card);
padding: var(--p-card);
}Why This Matters
- Dark Mode is Trivial: You don't rewrite component CSS. You just redefine the semantic tokens at the
:rootlevel inside a media query (or a.darkclass). - Consistency by Default: You can't accidentally use
23pxpadding if you're forced to usevar(--spacing-6). - Theming: Want a high-contrast theme or a completely different brand palette for a white-label client? Just swap out the CSS file containing the
:rootvariables. The component logic doesn't change.
CSS variables aren't just for colors. Use them for animation durations, z-indexes, typography scales, and spacing. Build your foundation on them, and everything else gets easier.