Custom Properties (CSS Variables)
Master CSS custom properties for dynamic theming and reusable styles
Defining Custom Properties
Custom properties (CSS variables) start with -- and are accessed via var().
:root {
--color-primary: #6366f1;
--spacing-md: 1rem;
--font-size-base: 16px;
}
.button {
background: var(--color-primary);
padding: var(--spacing-md);
font-size: var(--font-size-base);
}
Inheritance & Cascading
Custom properties inherit through the DOM. Override at any level.
.card {
--border-radius: 8px;
}
.card.featured {
--border-radius: 16px;
}
.card * {
border-radius: var(--border-radius);
} /* all children inherit */
Custom properties cascade normally, so a value defined on an element applies
to its children. Use :root for globals, specific selectors for scoped
overrides.
var() with Fallbacks
Provide a fallback in case the variable isn't set.
.card {
/* Fallback: #ccc if --color-surface is not defined */
background: var(--color-surface, #ccc);
/* Nested fallback: use --color-primary if set, otherwise --color-blue, otherwise #333 */
color: var(--color-primary, var(--color-blue, #333));
}
Dynamic Theming
Swap property values at a higher level to change the entire theme.
[data-theme="dark"] {
--color-bg: #0f172a;
--color-text: #e2e8f0;
--color-accent: #818cf8;
}
[data-theme="light"] {
--color-bg: #ffffff;
--color-text: #1e293b;
--color-accent: #6366f1;
}
body {
background: var(--color-bg);
color: var(--color-text);
}
:root {
--color-bg: #fff;
--color-primary: #6366f1;
}
[data-theme="dark"] {
--color-bg: #0f172a;
--color-primary: #818cf8;
}
@property for Typed Properties
Register custom properties with a syntax type, initial value, and inheritance. Enables animating properties that CSS can't normally interpolate.
@property --gradient-angle {
syntax: "<angle>";
initial-value: 0deg;
inherits: false;
}
.box {
--gradient-angle: 0deg;
background: linear-gradient(var(--gradient-angle), #6366f1, #a78bfa);
transition: --gradient-angle 1s;
}
.box:hover {
--gradient-angle: 360deg;
}
1<div class="theme-section">2<button class="toggle">Switch Theme</button>3<div class="demo-card">4 <h3>Themed Card</h3>5 <p>This card uses CSS custom properties for colors.</p>6</div>7</div>A toggle button switches CSS custom property values at the container (`theme-section`) level, demonstrating how theming works by overriding property defaults through inheritance.