Converts pixels to EMs with Sass

If you like using pixel values but understand that having your fonts set in EMs works better, especially when tackling responsive web design then this little Sass function will become super handy.

This function automatically converts pixels to EMs with Sass so that you don’t have to manually calculate them.

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);
}

5 Comments

  1. FWIW there’s a simple rem mixin as well, which I picked up originally from @malarkey I think:

    https://gist.github.com/growsnippets/5451223

    rems are the future!

    • Nice one! Thanks for the heads up.

  2. There is a way to address this without using interpolation in the function. There is a rem version as well.
    https://github.com/Toadstool-Stipe/stipe/blob/master/stylesheets/stipe/typography/_functions.scss

    The mixin idea above is interesting, but it feels weird to always include a mixin for standard CSS properties? Using a function with a CSS property just feels cleaner.

  3. One issue I’ve encountered with this is when it’s used for both padding and font-size at the same time the calculations are wrong. For instance I have a base font size of 13px and I’m setting the font to 14px using em(14), I also want a padding of em(14), instead of setting 1em after recalculating the font it’s doing them both at the same time.

  4. Actually my bad, I just realised you can pass in the context as an argument when adding padding etc.

This post currently has 5 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

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

Current ye@r *