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:
- Check the Type: We first ensure that the input
$numberis indeed a number and that it has a unit. - Create a Unitless Number: We multiply the number by
0and add1to create a temporary unitless number ($temp). This preserves the magnitude while stripping the unit. - Calculate the Unitless Value: We use
calc()to divide the original number by our temporary unitless number, effectively removing the unit. - 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.

Leave a Reply