What are CSS custom properties (variables) and how do you use them?

· Category: HTML & CSS

Short answer

CSS custom properties, also called CSS variables, are reusable values defined with -- and accessed with var(). They support inheritance, scoping, and runtime updates via JavaScript.

How it works

Declare a variable inside any selector. It is available to that element and its descendants. For global variables, define them on :root. You can provide fallback values inside var().

Example

:root {
  --primary: #005f73;
  --radius: 8px;
  --spacing: 1rem;
}

.card {
  background: var(--primary);
  padding: var(--spacing);
  border-radius: var(--radius);
  color: var(--text, #fff); /* fallback */
}
document.documentElement.style.setProperty('--primary', '#e63946');

Why it matters

Custom properties eliminate repetition, make theming straightforward, and allow dynamic styling without pre-processor compilation. They are especially powerful for dark mode toggles and design systems.