CSS: What’s the difference between em and rem?
If you have tried working with CSS, you'll have noticed two special units:
rem. If you compute one of each on a blank HTML page, they compile the same — so what's the difference?
First of all,
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,
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.
But why use
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
font-size and used it to calculate its own
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!