DEV Community

Discussion on: Convert px to rem Using Sass - 3 methods

Collapse
 
rekomat profile image
René Keller

Thanks Nikola! No matter which of the three methods you prefer, I would suggest two improvements.

  1. Convert the value instead of adding the unit.
// Add unit to value
font-size: 1 + rem + 1rem; // → string '1rem1rem'
// Convert unit
font-size: 1 * 1rem + 1rem; // → 2rem
Enter fullscreen mode Exit fullscreen mode
  1. Use math.div for division instead of / operator as using / for division is deprecated and will be removed in Dart Sass 2.0.0.
@use 'sass:math';

@function pxToRem($pxValue) {
    @return math.div($pxValue, 16px) * 1rem; 
}

div {
    width: pxToRem(400px); // → 25rem
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gleenk_20 profile image
Davide

Amazing, it's fully supported!