Convert Pixels to ems with Sass

Hack or Fix 188 views
0 Flares 0 Flares ×

The function takes two arguments, pixels and context. You can either use the default context and specify only the pixels you want to convert — or you can specify pixels and a custom context for the conversion.

$browser-context: 16; // Default

@function em($pixels, $context: $browser-context) {
  @return #{$pixels/$context}em

Then in your CSS just use pixel values and they will get automatically converted to ems.

body {
  font-size: em(16);

h1 {
  font-size: em(72);

h2 {
  font-size: em(24);
Provided by: Web Design Weekly
Tagged with:
Posted in Sass


One comment on “Convert Pixels to ems with Sass
  1. Riccardo De Contardi says:

    I’d prefer this way:

    @function strip-unit($num) {
    @return $num / ($num * 0 + 1);

    @function em($value, $context: $browser-context) {
    $value: strip-unit($value) / strip-unit($context) * 1em;
    @if ($value == 0em) { $value: 0; }
    @return $value;

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

No Trackbacks.


Register | Lost your password?
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×