rem units are generally considered the better way to size text and padding and various other things in CSS. But sometimes it can be difficult to realign your thinking with rem instead of pixels and it can be outright annoying when you are working off of a design measured in pixels but need to convert each value to rem.
Using Sass we can make all of this a non-issue. Below is a Sass function that takes in a pixel value and gives back a rem value.
Function
// tell sass to import the math library
@use "sass:math";
// Use toRem() to convert a pixel value to a rem value
// rem values help with accessibility, use anywhere a pixel value would be used
@function toRem($value) {
// if your default browser font size has changed from 16px, make the appropriate change below
$remValue: math.div($value, 16) + rem;
@return $remValue;
}
Calling it
// tell sass to import the math library
@use "sass:math";
// Use toRem() to convert a pixel value to a rem value
// rem values help with accessibility, use anywhere a pixel value would be used
@function toRem($value) {
// if your default browser font size has changed from 16px, make the appropriate change below
$remValue: math.div($value, 16) + rem;
@return $remValue;
}
h1 {
// Put in a pixel value here and a rem value will be produced on build
font-size: toRem(24);
}