Custom properties (--name) let you define colors, spacing, and fonts once in :root, then reuse them across components. Changing theme becomes a one-line update.
Define and consume
:root {
--brand: #4f46e5;
--surface: #ffffff;
}
.card { background: var(--surface); border-color: var(--brand); }
Scoped variables
You can set variables on a component (e.g. .card { --card-pad: 1rem; }) so variants do not pollute the global theme.
Practice
- Toggle
data-theme="dark"on<html>in the playground (uncomment the attribute). - Add a new token
--radiusand use it on buttons and cards.
Important interview questions and answers
- Q: CSS variables vs Sass variables?
A: CSS variables are live in the browser and can change at runtime; Sass compiles away at build time. - Q: Where are custom properties inherited?
A: They inherit like other properties—define on `:root` for global defaults. - Q: Fallback in `var()`?
A: `var(--brand, #000)` supplies a backup if undefined.