em is borrowed from the typography world, and it’s a unit that allows setting the font-size of an element relative to the font-size of its parent.
Let’s take this simple example:
.parent {
font-size: 18px;
}
.child {
font-size: 1.5em;
}
Copy
With that example, the child would have a font-size of 27px (1.5 * 18px = 27px).
If the parent element doesn’t specify a value for font-size, a value will be looked for higher up in the DOM tree. If no font-size is specified all the way up to the root element (<html>
), then the browser default of 16px is used.
Pretty simple and straight-forward right? em units can be used for much more than just setting font-size however, and they can be used pretty much everywhere units are expected (padding, margin, width, height, max-width,…you get the picture!) When em units are used on other properties than font-size, the value is relative to the element’s own font-size.
Let’s add to our example:
.parent {
font-size: 18px;
}
.child {
font-size: 1.5em;
padding: 2em 1em;
}
The rem unit, short for root em is a relative unit that’ll always be based upon the font-size value of the root element, which is the <html>
element. And if the <html>
element doesn’t have a specified font-size, the browser default of 16px is used.
So that means that, by using the rem unit, the values of parent elements are ignored, and only the value of the root is taken into consideration.
With a similar example, but in rem:
.html {
font-size: 16px;
}
.parent {
font-size: 15px;
}
.child-rem {
font-size: 2rem;
}
Copy
<div class="parent">
I'm 15px
<div class="child-rem">
I'm 32px, as expected
<div class="child-rem">
I'm 32px, yep!
<div class="child-rem">
I'm 32px, like clockwork!
</div></div></div></div>