Declaring Variables
/* Global scope — available everywhere */
:root {
--color-accent: #6366f1;
--color-bg: #060b14;
--color-text: #dde8f8;
--spacing-md: 16px;
--radius-lg: 12px;
--font-sans: 'Plus Jakarta Sans', system-ui, sans-serif;
}
/* Scoped to a component */
.card {
--card-padding: 20px;
--card-bg: #0e1628;
}
Using Variables with var()
button {
background: var(--color-accent);
color: var(--color-text);
padding: var(--spacing-md);
border-radius: var(--radius-lg);
font-family: var(--font-sans);
}
/* In calc() */
.grid {
gap: calc(var(--spacing-md) * 2); /* 32px */
}
/* In other properties */
.overlay {
background: rgb(from var(--color-accent) r g b / 0.2);
}
Scope & Inheritance
/* Variables cascade and inherit — override per component */
:root { --accent: #6366f1; }
.dark-section {
--accent: #a5b4fc; /* override for this section and children */
}
/* Theme switching */
[data-theme="dark"] {
--bg: #060b14;
--text: #dde8f8;
}
[data-theme="light"] {
--bg: #ffffff;
--text: #0f172a;
}
Fallback Values
/* var(--property, fallback) */
color: var(--custom-color, #6366f1);
/* Chained fallbacks */
color: var(--primary, var(--accent, #6366f1));
/* Fallback with space (for custom properties that need it) */
margin: var(--spacing, 0 16px);
💡 Note: If a custom property is defined but has an invalid value for its context (e.g.
--size: red used in width: var(--size)), the property becomes invalid at computed value time and falls back to inherited or initial value — not the fallback in var().JavaScript Interaction
// Read a CSS variable
const accent = getComputedStyle(document.documentElement)
.getPropertyValue('--color-accent').trim();
// → '#6366f1'
// Set a CSS variable
document.documentElement.style.setProperty('--color-accent', '#ec4899');
// Set on a specific element
card.style.setProperty('--card-bg', '#1a2d45');
// Remove a variable
document.documentElement.style.removeProperty('--color-accent');
// Useful for dynamic theming
function setTheme(hue) {
document.documentElement.style.setProperty('--hue', hue);
}