Interpolation: Sass Variables Inside calc()

Image by Maik Jonietz.

Perhaps one of the most common pitfalls I see with developers new to Sass is misunderstanding how Sass variables work, almost exclusively when used inside of calc().

September 2021: Dart Sass 1.40.0 introduced firstclass calculations. The interpolation workaround below documents the pre1.40 behaviour that applied when this article was published in May 2020; modern Dart Sass can use variables directly inside calc().

For example, during a recent code review:

$item_height: 50rem;.item {  min-height: calc(100% - $item_height);}

Logically, this should result in calc(100% - 50rem), and you should end up with an item that is 50rem shorter than the full 100% height. What actually gets generated is invalid CSS, with the variable name output into the raw CSS exactly as it was included in the Sass with no interpolation at all:

.item {  min-height: calc(100% - $item_height);}

Fortunately, once you realise where the issue lies, the solution is very easy and welldocumented:

Interpolation can be used almost anywhere in a Sass stylesheet to embed the result of a SassScript expression into a chunk of CSS. Just wrap an expression in #{ }.

In the specific case of calc(), its mathematical expressions conflict with Sass's arithmetic, so passing variables have to be interpolated first. Here's the same example as above again, but this time using interpolation:

$item_height: 50rem;.item {  min-height: calc(100% - #{$item_height});}

It is as simple as that!

However, there is one minor gotcha: interpolation injects a string, and not a value, which means that you cannot perform any further Sassbased arithmetic on the variable once it has been interpolated.

For example, this will not work: min-height: #{$item_height} - 10rem; because the variable has been interpolated before the -10rem calculation has been applied to it. Instead, any arithmetic has to occur inline, within the interpolation, like this: minheight: #{$item_height - 10rem};.

Interpolation prevents the surrounding calc() expression from being simplified or typechecked as one calculation. Sass still evaluates the SassScript expression inside #{...}, so incompatible units in that inner expression can still produce an error.


Untangling a delivery problem?

Send the symptoms, constraints, and affected routes. I'll help identify whether the issue sits in the application, platform, content model, deployment path, or search surface.