Sass Variables Versus CSS Custom Properties

Sass variables and CSS custom properties solve related but different problems.

A Sass variable such as $primary-color is resolved during compilation. A CSS custom property such as --primary-color is available in the browser's CSS cascade and can change dynamically based on inheritance, selectors, themes, and JavaScript.

Use Sass variables for compile-time constants and code-generation logic. Use CSS custom properties when a value needs to vary at runtime, respond to a theme class, inherit through the DOM, or be changed by JavaScript.

The two systems work well together. Sass can organize the token definitions while emitting CSS custom properties for runtime use.

Sass variables
Resolution: Compile time
The compiler substitutes values into generated CSS.
Scope: Sass module and lexical scopes
Access depends on Sass scope and module visibility.
CSS custom properties
Resolution: Browser runtime
Values participate in the CSS cascade.
Dynamic changes: Supported
Values can change through CSS rules or JavaScript.
Compile-Time and Runtime Tokens
$default-brand: #5b5bd6;

:root {
  --brand-color: #{$default-brand};
  --surface-color: #ffffff;
}

[data-theme="dark"] {
  --surface-color: #171717;
}

.button {
  background: var(--brand-color, #5b5bd6);
  color: white;
}

.page {
  background: var(--surface-color);
}
💡 Sass interpolates $default-brand into the CSS custom-property declaration. The resulting --brand-color and --surface-color values remain runtime CSS custom properties. A theme selector can change --surface-color without recompiling Sass. The browser resolves var() according to the CSS cascade and inheritance rules.
Knowledge Check

Which variable type is most suitable for switching a component theme dynamically in the browser?