CSS Variables Guide
Syntax
/* Define (must start with --) */
:root {
--color-primary: #6c63ff;
--color-text: #1a1a2e;
--spacing-unit: 8px;
--border-radius: 4px;
--font-size-base: 16px;
}
/* Use with var() */
.button {
background: var(--color-primary);
padding: calc(var(--spacing-unit) * 2);
border-radius: var(--border-radius);
font-size: var(--font-size-base);
}
/* Fallback value */
.card {
background: var(--surface-color, #ffffff);
color: var(--text-color, black);
}
/* Nested var() as fallback */
.element {
color: var(--custom-color, var(--color-text, #333));
}
Dark Mode Theming
:root {
--bg: #ffffff;
--text: #1a1a2e;
--surface: #f5f5f5;
--border: #e0e0e0;
--primary: #6c63ff;
}
[data-theme="dark"],
@media (prefers-color-scheme: dark) {
:root {
--bg: #0d0d1a;
--text: #e8e8f0;
--surface: #1c2035;
--border: #2e3250;
--primary: #8b85ff;
}
}
/* Toggle via JS */
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark');
Component-Scoped Variables
/* Component defines its own defaults */
.card {
--card-bg: white;
--card-padding: 16px;
--card-radius: 8px;
--card-shadow: 0 2px 8px rgba(0,0,0,0.1);
background: var(--card-bg);
padding: var(--card-padding);
border-radius: var(--card-radius);
box-shadow: var(--card-shadow);
}
/* Override per instance */
.card--featured {
--card-bg: var(--primary);
--card-shadow: 0 4px 20px rgba(108, 99, 255, 0.4);
}
/* Override in context */
.dark-section .card {
--card-bg: #2a2a3e;
}
JavaScript Integration
// Read a CSS variable
const root = document.documentElement;
const primary = getComputedStyle(root).getPropertyValue('--color-primary').trim();
// "#6c63ff"
// Set a CSS variable
root.style.setProperty('--color-primary', '#ff6363');
// Remove an override (fall back to stylesheet value)
root.style.removeProperty('--color-primary');
// Animate via custom property (with @property)
@property --gradient-angle {
syntax: '<angle>';
initial-value: 0deg;
inherits: false;
}
@keyframes rotate {
to { --gradient-angle: 360deg; }
}
.animated {
background: conic-gradient(from var(--gradient-angle), #6c63ff, #ff6363);
animation: rotate 3s linear infinite;
}