Posted 5 days ago. Visible to the public.

Setting SASS variables as value for CSS custom properties

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.


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.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Dominic Beger
Last edit:
4 days ago
by Dominic Beger
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominic Beger to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more