Converts pixels to EMs with Sass

February 26, 2013

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