Interpolation: Sass Variables Inside calc()

Hero image for Interpolation: Sass Variables Inside calc(). Image by Maik Jonietz.
Hero image for '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().

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: minheight: #{$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 10};.

This type of inline calculation also bypasses builtin unit checking within Sass, which means that you will receive no warning if you inadvertently mix incompatible unit types; you will just get spurious and broken generated CSS that doesn't work as expected.


Categories:

  1. CSS
  2. Development
  3. Front‑End Development
  4. Sass