Theming with Custom Properties
What you'll learn: How to organize CSS custom properties into logical groups to build flexible, maintainable color schemes and themes.
The Core Idea
Think of custom properties like a well-organized toolbox. Instead of scattering individual tools (color values) randomly throughout your workshop, you group them by purpose: "paint colors," "trim colors," "accent colors." When you organize custom properties into logical theme groups at :root, you create a single source of truth that makes switching entire color schemes as simple as changing a few values in one place.
Building a Theme System
Start by grouping related properties together. Create logical categories like brand colors, semantic colors (success, warning, error), and UI element colors (backgrounds, borders, text):
:root {
/* Brand palette */
--color-primary: #3b82f6;
--color-secondary: #8b5cf6;
/* Semantic colors */
--color-success: #10b981;
--color-warning: #f59e0b;
--color-error: #ef4444;
/* UI colors */
--color-bg-page: #ffffff;
--color-bg-card: #f9fafb;
--color-text-primary: #1f2937;
--color-text-secondary: #6b7280;
--color-border: #e5e7eb;
}
Now your components reference these organized properties:
.card {
background-color: var(--color-bg-card);
color: var(--color-text-primary);
border: 1px solid var(--color-border);
}
.button-primary {
background-color: var(--color-primary);
}
To implement a dark theme, you only update the root variables—all components automatically adapt:
:root.dark-theme {
--color-bg-page: #111827;
--color-bg-card: #1f2937;
--color-text-primary: #f9fafb;
--color-text-secondary: #d1d5db;
--color-border: #374151;
}
Key Takeaway: Organizing custom properties into logical theme groups creates a maintainable system where changing an entire color scheme requires updating only a handful of variables, rather than hunting through hundreds of declarations.