Skip to content

Convert px to percent or em with SASS functions

When SASS introduced functions in v3.1.0 I could see their potential but up until now I hadn’t realized just how useful they could be; especially for things like turning px font size values into percentages.

This simple but extremely useful function has saved me so much time when calculating font sizes!

// PIXELS TO PERCENTAGES
// $target: the desired font size for the element
// $parent: the targets parent element font size (default: 16)
//------------------------------------------
@function pxtopercent($target, $parent: 16) {
  @return percentage($target / $parent);
}

// Default
.element {
  font-size: pxtopercent(11);
}

// With custom $parent value
.element {
  font-size: pxtopercent(11, 20);
}

If you prefer, you can also create a similar function for turning px into em‘s:

// PIXELS TO EMS
// $target: the desired font size for the element
// $parent: the targets parent element font size (default: 16)
//------------------------------------------
@function pxtoem($target, $context: 16) {
  @return ($target / $context)+0em;
}

// Default
.element {
  font-size:pxtoem(11);
}

// With custom $parent value
.element {
  font-size:pxtoem(11, 20);
}

Most of the projects I work on now are coded using SCSS. With the aid of simple functions like this, most seasoned CSS’ers should find the benefits of using SASS outweigh the potential pitfalls. Hopefully when rem, vw, vh, and vmin are more widely supported this kind of thing will become less of a problem; but until then SASS functions like this can be extremely helpful.