CSS Custom Properties: declaring and updating
Declare variables with -- on :root, reference them with var(), and update them dynamically with JavaScript for live theming.
Recap: Declaring and Scoping
CSS custom properties are declared with -- prefix on any element. Properties declared on :root are globally available. Child elements inherit the values, and can override them locally.
:root {
--spacing: 8px;
--color-brand: #6366f1;
}
.card {
--spacing: 12px; /* local override for .card and its children */
padding: var(--spacing);
}Live Updates via JavaScript
Custom properties can be changed at runtime. Use element.style.setProperty('--name', value) for element-level overrides, or update a global variable on :root to affect all consumers instantly.
// Change globally:
document.documentElement.style.setProperty('--color-brand', '#ef4444');
// Change locally on one element:
const card = document.querySelector('.card');
card.style.setProperty('--bg', '#f9f9f9');All lessons in this course
- CSS Custom Properties: declaring and updating
- Transitions: property duration timing
- @keyframes Animations
- Respecting prefers-reduced-motion