David Lohmeyer's Blog

Font sizing in CSS: em vs. px vs. rem

I've been looking for ways to simplify my CSS development constantly.  I recently made the switch to using Compass/SASS full time in all of my projects due to its simplicity and more importantly the fact that you can create a base template for all of the wild CSS3 effects that require 5 different lines for each browser.

That said, simplifying font sizing is also important.  I used to use 'px' sizing exclusively, but I realize for different screen sizes it became problematic.  Therefore I switched to using 'em' and setting my base font size to 62.5%.  What that lets you do is keep a base 10 so you can size a 14px body font using '1.4em' instead of some crazy math.

Unfortunately, em sizing is nested.  Thus, if you have elements with 1.4em and then nest some HTML with elements that also have an em declaration, their sizing multiplies.

This looks ugly, is confusing, and is harder to fix.  You can calculate the correct sizing or you can declare font size on individual elements (which is long and painful and defeats simplicity).

Instead, use "rem".  I found this post about using rem with Drupal 7 themes, but you can use it in any CSS dev.  What 'rem' does is base font size off of the root HTML element instead of nesting and multiplying font size.  Thus, if you say 1.4rem it actually means it's going to be the same, nested or not.

It doesn't work in older IE, so you'll have to do two declarations.  For example, for a p tag definition:

p{
  font-size: 14px;
  font-size: 1.4rem;
}

Don't forget to put this in your html CSS:

html{
  font-size: 62.5%;
}

Rem also scales from screen size like em as far as I know, so you get the advantages while ditching the math and complexity.

Looking for a good book that explains CSS font sizing?  Check out Implementing Responsive Design: Building sites for an anywhere, everywhere web by Tim Kadlec.

Related Posts