Skip to main content

CSS Variables and SASS

· One min read
Philipp Tessenow

Both, SASS and CSS support variables, and of course they are not the same:

  • SASS variables get compiled into actual values into final CSS files.
  • CSS variables can be used as variables in the browser.

Today we had a fun debugging session while combining the two. We learned that you can’t put SASS variables into a CSS-variable just like that:

    $my-sass-var = #C0FFEE;

:root {
--my-css-var: $my-sass-var;
}

When compiling, it generates the exact input text in the compiled css file (we expected $my-sass-var to be replaced by the SASS compiler with #C0FFEE).Using SASS variables like this works almost everywhere, except when using CSS variables. It seems the SASS compiler thinks $my-sass-var is already proper CSS.

This issue appears beginning with node-sass 4.8.3, libsass 3.5.2. It used to work before these versions. It’s not mentioned in any release notes that this broke.

The solution is to wrap the variable in #{}:

:root {
--my-css-var: #{$my-sass-var};
}

#{} triggers an explicit SASS interpolation, forcing the compiler to treat $my-sass-var as SASS code which needs compilation.

Philipp Tessenow

Philipp Tessenow

Tech-nerd & Intranet-gangster

We’re hiring

Work with our great team, apply for one of the open positions at bitcrowd