CSS Custom Properties Advanced
5 min read
Build a spacing scale with custom properties: --space-4: 1rem, --space-8: 2rem. Scope variables to components to create component CSS APIs. Chain fallbacks: var(--brand, var(--primary, blue)) for safe defaults.
Advanced CSS Variables
/* Responsive spacing scale */
:root {
--space-1: 4px;
--space-2: 8px;
--space-3: 16px;
--space-4: 24px;
--space-5: 48px;
}
/* Fallback value */
color: var(--primary, #3b82f6);
/* Inherit through DOM */
.themed {
--color: tomato;
}
.themed .child {
color: var(--color); /* inherits tomato */
}
/* Override via attribute */
[data-color="blue"] { --color: blue; }