Back to Garden
Note
Quick Tip: CSS Variables for Theming
A simple pattern for building theme-aware components using CSS custom properties.
Peter
#css#theming#quick-tip
CSS Variables for Theming
A quick pattern I use for theme-aware components.
The Setup
Define semantic tokens in your root:
:root {
--ui-bg: #ffffff;
--ui-text: #1a1a1a;
--ui-primary: #0066cc;
}
.dark {
--ui-bg: #1a1a1a;
--ui-text: #ffffff;
--ui-primary: #66b3ff;
}Usage in Components
Reference these in your components:
.card {
background: var(--ui-bg);
color: var(--ui-text);
border: 1px solid var(--ui-border);
}
.button-primary {
background: var(--ui-primary);
color: var(--ui-bg);
}Why This Works
- Single source of truth - Change theme colors in one place
- No JavaScript needed - Pure CSS solution
- Runtime changes - Toggle
.darkclass to switch themes - Cascading - Override tokens for specific sections
Pro Tip
Use CSS variables for spacing and typography too:
:root {
--space-sm: 0.5rem;
--space-md: 1rem;
--space-lg: 2rem;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.25rem;
}That’s it! Simple but powerful. 🎨