A CSS variable (formally called a custom property) lets a value — a color, a spacing size, a font — be defined once and reused throughout a stylesheet, updated everywhere at once from a single place.
A variable name always starts with two dashes. Defining it on :root makes it available everywhere on the page.
:root {
--brand-color: #3366ff;
--spacing-unit: 8px;
--font-heading: 'Poppins', sans-serif;
}.button {
background-color: var(--brand-color);
padding: var(--spacing-unit);
}
h1 {
font-family: var(--font-heading);
}var() accepts a second argument — used if the variable isn't defined.
.button {
color: var(--text-color, black);
}A variable defined inside a specific selector, rather than :root, is only available within that element and its children.
.dark-card {
--card-bg: #1a1a1a;
--card-text: white;
background-color: var(--card-bg);
color: var(--card-text);
}Unlike a Sass variable, a CSS custom property is live in the browser — it can be read and changed with JavaScript, and it responds instantly to a media query or a class toggle, without a rebuild step.
document.documentElement.style.setProperty('--brand-color', '#ff3366')A practical pattern
A common real use: define color and spacing variables once at :root, then override just a handful of them inside a .dark-theme class to build a dark mode without duplicating every rule.