CSS Custom Properties (Variables)
CSS custom properties (also called CSS variables) let you define reusable values that cascade through the DOM. They replace the need for preprocessor variables (Sass $variables) in many cases, and unlike Sass, they can be changed dynamically with JavaScript and respond to media queries.
40 min•By Priygop Team•Last updated: Feb 2026
Custom Properties Usage
- Declaration — :root { --primary: #E44D26; --spacing-lg: 24px; }. The -- prefix is required
- Usage — color: var(--primary); padding: var(--spacing-lg). var() function accesses the value
- Fallback — var(--color, #333) uses #333 if --color is undefined. Chain fallbacks for resilience
- Scoping — Variables cascade. Define on :root for global, on .component for scoped. Children inherit parent variables
- Dynamic — Change with JS: element.style.setProperty('--primary', '#667eea'). React to user input in real-time
- Media queries — Redefine variables in @media blocks to change theming without touching component styles
- calc() integration — width: calc(var(--sidebar) + var(--gap)). Combine variables with calculations
Design System with CSS Variables
Example
/* Complete design system with CSS variables */
:root {
/* Colors */
--primary: #E44D26;
--primary-hover: #c0392b;
--secondary: #667eea;
--success: #2ecc71;
--danger: #e74c3c;
--text: #1a1a2e;
--text-light: #666;
--bg: #ffffff;
--bg-alt: #f8f9fa;
--border: #e0e0e0;
/* Spacing scale */
--space-xs: 4px;
--space-sm: 8px;
--space-md: 16px;
--space-lg: 24px;
--space-xl: 32px;
--space-2xl: 48px;
/* Typography */
--font-sans: 'Inter', -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', monospace;
--text-sm: 0.875rem;
--text-base: 1rem;
--text-lg: 1.125rem;
--text-xl: 1.25rem;
--text-2xl: 1.5rem;
/* Borders & shadows */
--radius-sm: 6px;
--radius-md: 12px;
--radius-lg: 16px;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.08);
--shadow-md: 0 4px 12px rgba(0,0,0,0.1);
--shadow-lg: 0 8px 24px rgba(0,0,0,0.15);
}
/* Dark mode — just redefine colors */
@media (prefers-color-scheme: dark) {
:root {
--text: #e0e0e0;
--text-light: #a0a0b0;
--bg: #1a1a2e;
--bg-alt: #16213e;
--border: #2a2a4a;
}
}
/* Using the system */
.btn {
background: var(--primary);
color: white;
padding: var(--space-sm) var(--space-lg);
border-radius: var(--radius-sm);
font-family: var(--font-sans);
}
.btn:hover { background: var(--primary-hover); }
.card {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: var(--space-lg);
box-shadow: var(--shadow-sm);
}