Skip to main content

Convert PX to EM With SASS/SCSS Mixin

By November 30, 2015SASS/SCSS, Snippets
Allure Web Solutions Code Snippet

What is an “EM”? Why is it important?

The Mozilla Developer Network has a very succinct explanation of what ems are:

…an em is equal to the size of the font that applies to the parent of the element in question. If you haven’t set the font size anywhere on the page, then it is the browser default, which is probably 16px. So, by default 1em = 16px, and 2em = 32px.

EM’s importance can be summarized in a few words: You will want to adjust spacing and font sizes for different screen sizes. A font that looks good on the phone, will not necessarily look good on a large desktop screen.

How do we want to implement our EMs in our web app? First of all start by giving the html and body tags their respective starting definitions:

html { font-size: 100%; /* 16px */ }
body { font-size: 1em; /* 16px */ }

Now if you use 1em for an font size, that font will be 16px. Let’s say you want a font size that is 12px, you would use 0.75em.

Every pixel value can be expressed in terms of EMs, not only font sizes. For example, if you want 32px padding on a div element, you can use:

div { padding: 2em; /* 32px */ }

You should define all of your px values in terms of EMs, because the main beauty of EMs is that they are relative to their parent elements. What’s the significance of this?

Imagine you want to bump up the font of everything on your website by 2px. You can do this by setting the body font size to 1.125em. This would cascade down to all of your font definitions throughout your style sheets if you have used EMs. However, if you defined static PX values for fonts, this will have no effect.

Let’s consider this scenario a little further. You’ve now increased your fonts by 2px, but the borders between divs and your overall layout has been statically set with PXs. This means the now larger fonts might not look as good with the previously defined spacing of elements. If you had set your paddings and margins with EMs instead, then those would proportionally increase as well when adjusting the base font size!

Hopefully you are now a believer in EMs. But, surely you still think in terms of PXs. Tell me now off the top of your head how many EMs 17px is! Did you say 1.063em? As you can see, it can be hard to convert inside your head. That’s why we can use a handy SASS mixin for this. You never have to convert manually!

$browser-context: 16; // Default

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

Now we can define everything using EMs extremely easily:

h1 { font-size: em(18); /* 18px */ } // OUTPUT: h1 { font-size: 1.125em; }
div { padding: em(10) em(20); } // OUTPUT: div { padding: 0.625em 1.25em; }
allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017