GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

To em, or to err.

There's been some talk about ditching ems as the proper unit for measuring type in stylesheets. This is as many things are; while possible, probably not a great idea.

Units allow us to speak on common ground. Almost everything has a unit of measure. For type, we use ems. so what's an 'em'?

em: the square of a body of any size of type

The argument for ditching ems suggests instead defining font size in pixels. How 1999 of you. Pixels are a unit of measure for bitmap images. This may shock some of you, but images and type are not the same. Think about it this way - would you measure BAC in dB?

IE6 doesn't allow resizing of pixel-sized type. There's a reason for this. How do you resize a pixel? Better yet, how do you easily standardize something like that?

So we've covered why not to use pixels - but why ems? Because they're relative units. Get back here, coward!

This can be easy.

Let's start with a simple case. We set our base text-size to 10px, or 1em (62.5% of 16px which is a typical browser default). That makes the following math a bit friendlier.


body {
  font-size: 62.5%
}

Next we decide a typographic scale.


h1 {
  font-size: 2.4em;
}

p {
  font-size: 1.2em;
}

This part is optional, but the classic scale has worked well for type setters for centuries. I'd recommend sticking to one. Next we define a standard line-height of 1.8em.


h1 {
  font-size: 2.4em;
  line-height: .75em;
}

p {
  font-size: 1.2em;
  line-height: 1.5em;
}

To get these values, divide your font-size by the desired line-height value. For example, take 1.8 (our line-height) and divide by 2.4 (the font-size of h1). Your result (.75) is the line-height for h1.

So far, basic arithmetic. Still with us? Great! Let's add a 'line' between each paragraph, and set some appropriate margins on our headers.


h1 {
  font-size: 2.4em;
  line-height: .75em;
  margin: .75em 0;
}

p {
  font-size: 1.2em;
  line-height: 1.5em;
  margin-bottom: 1.5em;
}

I bet I know what you're thinking. Where does he come up with these crazy numbers? Hint: Check the line-height value.

Okay, so now let's handle the heckler in the back of the room. Here's how I'd probably handle some pesky h2's.


h1 {
  font-size: 2.4em;
  line-height: 0.75em;
  margin: .75em 0;
}

h2 {
  font-size: 1.8em;
  line-height: 1em;
  margin: 1em 0;
}

p {
  font-size: 1.2em;
  line-height: 1.5em;
  margin-bottom: 1.5em;
}

It fits in our typographic scale. Our design holds up. If you're curious about how all this looks I've thrown together a quick example using h3's as well. My solution? Knock all the headers up one notch on the scale.

Things can get out of hand if you start with unsound values, or start mixing units of measure. But stick to your guns! It lends tremendous persuasive resources, and provides benefits that justify the foresight of this technique.

If you want to learn more, here's a bit of related reading.