Don’t hesitate to contact us if you have any feedback.

SCSS – Remove units from numbers

In the realm of CSS preprocessing, we often encounter situations where we need to perform calculations or pass values to functions that expect unitless numbers. However, numbers in CSS often come with units like pixels (px), ems (em), or percentages (%), which can be problematic in such cases.

Introducing the strip-unit Function

To address this issue, we have created a SCSS function named strip-unit.

The Code

@use 'sass:math';
@use 'sass:meta';

@function strip-unit($number) {
  @if meta.type-of($number) == 'number' and not math.is-unitless($number) {
    $temp: $number * 0 + 1;
    @return calc($number / ($temp));
  }

  @return $number;
}

Let’s break down how this function works:

  1. Check the Type: We first ensure that the input $number is indeed a number and that it has a unit.
  2. Create a Unitless Number: We multiply the number by 0 and add 1 to create a temporary unitless number ($temp). This preserves the magnitude while stripping the unit.
  3. Calculate the Unitless Value: We use calc() to divide the original number by our temporary unitless number, effectively removing the unit.
  4. Fallback: If the number is already unitless or not a number, we simply return it as-is.

Usage and Benefits

By incorporating the strip-unit function into our SCSS codebase, we enable more flexible and error-free calculations. This function is particularly useful when working with dynamic values where the unit might be unknown or needs to be disregarded.

Conclusion

This strip-unit function is a practical tool for any developer working with SCSS. It simplifies the handling of units and ensures that our stylesheets remain clean and maintainable.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *