CSS Variable
In one line
A CSS variable (custom property) is a reusable value defined with --name and accessed with var(), enabling theming and DRY CSS.
In simple words
CSS variables (officially "custom properties") let you store values in a named variable and reuse them throughout your CSS. This makes it easy to maintain consistent design tokens (colors, spacing, fonts) and create themes.
You define a variable with a double dash: --primary-color: #2563eb; and use it with var(): color: var(--primary-color);. Variables follow the cascade and can be overridden at any level — define global ones on :root and override locally on specific elements.
CSS variables are more powerful than preprocessor variables (Sass/Less) because they are dynamic — they can change at runtime with JavaScript, respect media queries, and cascade through the DOM. This makes them ideal for dark mode, theming, and responsive design.
Example
:root {
--primary: #2563eb;
--spacing: 1rem;
}
.button {
background: var(--primary);
padding: var(--spacing);
}
/* Dark mode override */
@media (prefers-color-scheme: dark) {
:root { --primary: #3b82f6; }
}CSS variables for theming, with a dark mode override using a media query.
Related terms
Related Resources
Related Lessons
- CSS Variables
Learn CSS variables.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.