CSS Variables
CSS Variables (Custom Properties) provide direct access to all design tokens in your stylesheets. They enable dynamic theming, easier maintenance, and more predictable styling across components.
What Are CSS Variables?
CSS Variables (also called CSS Custom Properties) are entities defined by CSS authors that contain specific values to be reused throughout a document. They provide:
- Dynamic theming capabilities
- Single-source-of-truth for design decisions
- Reduced code duplication
- Easier maintenance and updates
Syntax
Variable Naming Convention
All CSS variables follow the pattern: --{category}-{property}
Examples
Colors
Typography
Spacing
Other
Color Variables
Background Colors
Used for page backgrounds, containers, and surface layers:
Usage:
Foreground Colors
Text and foreground elements:
Usage:
Accent Colors
Primary interactive elements and highlights:
Usage:
Semantic Colors
Success (Green)
Danger (Red)
Warning (Yellow)
Info (Blue)
Usage:
Typography Variables
Font Family
Usage:
Font Sizes
Usage:
Font Weights
Usage:
Line Heights
Usage:
Complete Text Styles
Pre-combined typography variables:
Usage:
Spacing Variables
Spacing uses 4px as the base unit:
Usage:
Border Radius Variables
Usage:
Shadow Variables
Usage:
Motion Variables
Duration
Easing
Usage:
Practical Examples
Button Component
Form Element
Card Component
Alert Component
Theme Switching
CSS variables make theme switching simple and efficient:
JavaScript Theme Switching:
Browser Support
CSS Variables are supported in all modern browsers:
- Chrome 49+
- Firefox 31+
- Safari 9.1+
- Edge 15+
- All modern mobile browsers
Fallback Values
For older browser support, provide fallback values:
Performance Considerations
Advantages
- Zero runtime cost: Variables are parsed at parse time
- Smaller CSS: Reduces code duplication
- Faster theme switching: No need to recompile stylesheets
Best Practices
- Define variables at
:rootfor global scope - Use local variables for component-specific values
- Avoid excessive nesting of variables
- Use meaningful names that reflect purpose
Debugging
Inspecting Variables
In the browser DevTools:
Common Issues
Variable not working:
- Check spelling and hyphenation
- Verify it's defined in
:rootor parent scope - Ensure fallback value is valid CSS
Theme not switching:
- Verify CSS selector matches HTML element
- Check that variables are redefined in new scope
- Clear browser cache
Migration Guide
From Hardcoded Values
Before:
After: