CSS: What’s the difference between em and rem?

If you have tried working with CSS, you'll have noticed two special units: em and rem. What's the difference?

CSS: What’s the difference between em and rem?

If you have tried working with CSS, you'll have noticed two special units: em and rem. If you compute one of each on a blank HTML page, they compile the same — so what's the difference?

First of all, em and rem are dynamic units. They scale depending on the font size. In fact, in a standard HTML page, where the default font size is 16px, 1em and 1rem both compile to 16px.

The difference lies in that little "r": it stands for root. The practical difference is that while em compiles to px using the element's font-size (or the inherited one), rem uses the one in the root element (<html>). It's also important to mention that rems are just a CSS3 thing; they don't exist in previous versions.

em refers to "the width of the letter M" because before the computer era, press typefaces usually made the uppercase M to be a "block" wide. Nowadays, the letter M is usually narrower than 1 em, but the terminology stayed.

One em was traditionally defined as the width of the capital M in the current typeface and point size, because the M was commonly cast the full-width of the square blocks, or em-quads (also mutton-quads), which are used in printing presses.

In modern typefaces, the character M is usually somewhat less than one em wide.
Wikipedia

But why use em and rem? Because the content should adjust to the size of the device, it is important that your font adjusts too.

You've gotta be careful with em though. Take this example:

Even though you set the font-size on the p element to 1em, it inherited the div's 2rem font-size and used it to calculate its own 1em font-size, resulting in 16px * 2rem * 1em = 32px. Had we used 1rem on it instead, it would've been half the size:

Alright, that's it for today's story. Happy programming!