What are CSS custom properties (variables) and how are they used?

LowIntermediateCss
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

CSS custom properties (variables) are declared with --name and read with var(--name). They inherit, can be scoped, and enable theming or design tokens without preprocessors. Great for theming, but fallbacks and inheritance are edge cases; test dynamic theme toggles.

Answer

Overview

CSS custom properties are variables defined with the -- prefix and accessed using the var() function. They differ from preprocessor variables (like SASS or LESS) because they’re live in the browser — inheritable, changeable with JavaScript, and scoped within selectors.

CSS
:root {
  --main-color: #0070f3;
  --accent-color: #ff4081;
  --spacing: 1.5rem;
}

button {
  background-color: var(--main-color);
  color: white;
  padding: var(--spacing);
  border: none;
  border-radius: 8px;
}

button:hover {
  background-color: var(--accent-color);
}
                  

Scoping & Inheritance
Variables defined in :root are global. They can be overridden locally inside specific components or containers, enabling theming or context-aware customization.

CSS
.dark-theme {
  --main-color: #222;
  --accent-color: #0ff;
}

.card { background-color: var(--main-color); color: var(--accent-color); }
                  

Dynamic Updates with JavaScript
Unlike preprocessor variables, custom properties exist in the DOM and can be modified at runtime.

JAVASCRIPT
document.documentElement.style.setProperty('--main-color', '#e63946');
                  

Fallback Values
Use fallback values when a variable might not exist:
color: var(--heading-color, #333);

Best Practices

    <li>Define global tokens in :root for theme consistency.
      • Use local overrides for component variants or dark/light modes.
      • Combine with media queries for responsive design (@media (prefers-color-scheme: dark)).
      • Maintain a naming convention like --color-primary, --spacing-md.

Custom properties are like CSS ‘globals’ that react dynamically to context — perfect for modern design systems and theme engines.

Practical scenario
Implement light/dark themes by switching CSS variables on :root and letting components react automatically.

Common pitfalls

      • Missing fallbacks when variables are undefined.
      • Confusing CSS variables (runtime) with preprocessor variables (build-time).
      • Scoping variables too narrowly so children cannot inherit them.
Trade-off or test tip
Variables allow runtime theming but require careful defaults. Test by toggling themes and verifying contrast and inheritance.

Similar questions
Guides
14 / 30