Append unit type to the result of a calculation in Sass

The only way to add a unit to a number is via arithmetic.

To perform operations like concatenation (eg. 1 + px) or interpolation (eg. #{1}px) will only create a string that looks like a number. Even if you're absolutely 100% certain that you're never going to use your value in another arithmetic operation, you should not do this.

More important than not being able to perform arithmetic operations, you won't be able to use them with other functions that expects a number:

$foo: 1; // a number
$foo-percent: $foo + '%'; // a string

.bar {
    color: darken(blue, $foo-percent); //Error: "1%" is not a number!
}

$amount: "1%" is not a number for `darken'

There is nothing to be gained by casting your numbers to strings. Always use arithmetic (multiplication by 1, or addition by 0) to add a unit:

$foo: 1; // a number
$foo-percent: $foo * 1%; // still a number! //or: $foo + 0%

.bar {
    color: darken(blue, $foo-percent); //works!
}

Output:

.bar {
  color: #0000fa;
}

Here's a mixin I wrote as part of my Flexbox mixin library that will choke if you pass in a string (for those not familiar with Flexbox, the original specification only allows integers for the box-flex property. flex: auto or flex: 30em cannot be made compatible with the comparable box-flex property, so the mixin doesn't bother trying)

@mixin flex($value: 0 1 auto, $wrap: $flex-wrap-required, $legacy: $flex-legacy-enabled) {
    @if $legacy and unitless(nth($value, 1)) {
        @include legacy-flex(nth($value, 1));
    }

    @include experimental(flex, $value, flex-support-common()...);
}

@mixin legacy-flex($value: 0) {
    @include experimental(box-flex, $value, $box-support...);
}

You can try either of these:

font-size: $size * 1px;

or

font-size: $size + unquote("px");

Where $size is the result of your calculation.

Tags:

Css

Sass