Setting SASS variables as value for CSS custom properties

Posted . Visible to the public.

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)

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.

Dominic Beger
Last edit
Dominic Beger
License
Source code in this card is licensed under the MIT License.
Posted by Dominic Beger to makandra dev (2021-07-20 13:33)