Skip to content

Instantly share code, notes, and snippets.

@leonkorteweg
Last active March 21, 2016 12:49
Show Gist options
  • Save leonkorteweg/aa28469f3be42048ac23 to your computer and use it in GitHub Desktop.
Save leonkorteweg/aa28469f3be42048ac23 to your computer and use it in GitHub Desktop.
EM units in media queries

Using EM units in media queries

Zell Liew did some research on em, px and rem units in media queries. In his article he shows that pixel units should not be used in media queries. Instead we should use em units. The main reason is that the pixel based values don't work properly in Safari. When a user increases the font size of the page, the pixel based media queries don't scale accordingly.

Converting pixel units to em in media queries

Here is an example media query with pixel units:

@media only screen and (min-width: 800px) { … }

You can convert px units to em units by using the font-size on that element. In the case of the media query that is the <html> element. The default font size of the <html> element is 16px. You can calculate the em value from the example above by deviding 800px by the font-size, which is 16px. This gives us 50em.

@media only screen and (min-width: 50em) { … }

In Sass or SCSS you can also do:

@media only screen and (min-width: 800px / 16px * 1em) { … }

This way you'll remember the original pixel based value you decided on. It's also quicker, it makes switching to a calculator app unneccessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment