Read more

Setting SASS variables as value for CSS custom properties

Dominic Beger
July 20, 2021Software engineer at makandra GmbH

When using custom properties in your stylesheets, you may want to set a specific property value to an existing variable in your SASS environment. A pratical example would be a list of color variables that you've defined in colors.sass and that you would like to refer to in your stylesheets. However, simply assigning a variable will not work:

$my-great-blue: blue

:root
  --my-color: $my-great-blue

.sky
  background-color: var(--my-color)
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

The property value will not be valid and if you open the browser's inspection window, you will see that the computed value will still equal $my-great-blue instead of blue. The reason is that custom property values behave differently and allow any kind of value to be assigned (thus not being bound to CSS-context). The SASS compiler consequently preserves this functionality/behavior and the value you assign will be translated one by one.

In order to tell the SASS compiler that it should resolve the assigned value as variable, you have to escape it:

$my-great-blue: blue

:root
  --my-color: #{$my-great-blue}

.sky
  background-color: var(--my-color)

Now, the final CSS will contain your color code as expected.

Attention

Escaping inputs will remove any quotes from string values. Be careful when dealing with e.g. font-family definitions in variables.
In order to preserve existing quotes, you may use the meta.inspect() function:

@use "sass:meta"

$my-cool-font: "Roboto", sans-serif

:root
  --font-family-sans-serif: #{meta.inspect($my-cool-font)}

Unfortunately, the output of this function is not guaranteed to be consistent across all SASS versions as its primary purpose is debugging assistance.

Posted by Dominic Beger to makandra dev (2021-07-20 15:33)