Using math.div instead of / in scss

Viewed 24009

Need to rewrite this function using math.div instead of slash. Details mentioned in the URL given below.

https://jsfiddle.net/26ty5aj7

    @function px2em($px, $metric: 'em', $base-font-size: 16px) {
      @if unitless($px) {
        @warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels.";
        @return px2em($px * 1px, $metric, $base-font-size);
      } @else if unit($px) == em {
        @return $px;
      }  
      @return #{($px / $base-font-size) + $metric};
    }
    
    // Pixels to rem based on sass-mq
    @function px2rem($px) {
      @if unit($px) == rem {
        @return $px;
      }

      @return px2em($px, 'rem');
    }

@return #{($px / $base-font-size) + $metric};

1 Answers

Here are your functions with the updated syntax. Make sure to keep the @use import at the top of your file.

@use "sass:math";

@function px2em($px, $metric: 'em', $base-font-size: 16px) {
  @if unitless($px) {
    @warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels.";
    @return px2em($px * 1px, $metric, $base-font-size);
  } @else if unit($px) == em {
    @return $px;
  }
  $test: #{math.div($px, $base-font-size) + $metric};
  @return $test;
}

// Pixels to rem based on sass-mq
@function px2rem($px) {
  @if unit($px) == rem {
    @return $px;
  }

  @return px2em($px, 'rem');
}

Automated Migration

If you have many instances of division, you may want to take a look at the automatic migration tool provided by Sass, as thoughtfully pointed out by @Andreas in the comments.

# Install the tool globally using npm
npm install -g sass-migrator
# Run the codemod on all .scss files recursively from the working directory
sass-migrator division **/*.scss

# OR

# Use npx to install temporarily and immediately run (similar to above)
npx --yes sass-migrator division **/*.scss

Compatibility

Keep in mind that the deprecation is a transition, and math.div is currently only supported in Dart Sass (sass on npm) >=1.33.0 and not supported in Ruby Sass or LibSass (node-sass on npm).

This means it is safe to update when your Sass files are only compiled in your project. However, maintainers of libraries that export Sass, like Bootstrap for example, should be mindful as it could be a breaking change.

Related