obda.net

Convert px to rem with Sass

Add a comment

The following Sass function converts pixels to rem:

@function px-rem($size, $base: 16px) {
    @if (unitless($size)) {
        $size: $size * 1px;
    }
    @if (unitless($base)) {
        $base: $base * 1px;
    }
    @return 1rem * ($size / $base);
}

The $size argument can be provided either with or without a px unit, for example:

font-size: px-rem(18px);   /* 1.125rem */
line-height: px-rem(24);   /* 1.5rem */

You can provide a second argument to px-rem() if your base font size is not 16 pixels.