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.
Compile timeSass module and lexical scopesBrowser runtimeSupported$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);
}$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.Which variable type is most suitable for switching a component theme dynamically in the browser?