CSS variables are custom properties that hold reusable values throughout your stylesheet. Defined with double dashes (--), they can store colors, font sizes, spacing values, or any CSS value. Example: --primary-color: #3498db;
Declare variables in the :root selector for global access: :root { --primary: #3498db; --padding: 1rem; }. Use them with the var() function: color: var(--primary); padding: var(--padding);. You can also set fallback values: var(--primary, blue).
CSS variables make dark/light mode theming incredibly easy. Define color variables in :root for the light theme, then override them in a dark mode class or @media query. Update just the variable value and every usage updates automatically.
Unlike preprocessor variables (Sass/LESS), CSS variables can be changed at runtime. Use document.documentElement.style.setProperty("--primary", "#e74c3c") to update values on the fly. This enables live theme switching and interactive design.
CSS variables respect the cascade. Variables defined in a container only apply within that container and its children. This allows component-level theming. Override a variable in a specific section to create visual variations without duplicating CSS.
Use cases include: consistent color palettes across large projects, easy responsive design (change spacing variables at breakpoints), animation parameters (store durations and delays), and design system foundations. CSS variables are supported in all modern browsers.