How to interpolate Sass variables on CSS custom variables/properties

Thabo Ambrose
Nov 18, 2020

This is just a quick writing exercise about CSS & Sass variables, its not meant to teach but it can teach you something, I will not cover what CSS and Sass are.

A property name prefixed with double dashes like below is a CSS custom property that can be reused in the current rule-set scope.

--my-variable: #000

The variable’s value above can be assigned to another CSS attribute like below. Using the var func.

#myHeading {
color: var(--my-variable);
}

The CSS variable my-variable needs to be accessible in the #myHeading rule-set, to achieve this, you can have the variable defined in the stylesheet’s global scope using the :root selector which selects the document’s root element.

If you are using CSS together with Sass, you can have your Sass/SCSS variable defined in a separate file and then import that file and then you can use the variable’s value with a CSS custom varible like below:

--custom-css-var:  #{$scss-var};

The above rule uses Sass interpolation to get the value of the SCSS variable.

By using this approach you will not have to have the :root selector which will not scope your variables but will be global to the whole document.

I’m sure there’s lot to achieve with this, but I am not sure if its good practice to use CSS custom variables with Sass variables, I mean why not just use Sass variables, mixins etc?

--

--