While it's best practice to use
rem when defining font sizes, it's common for developers to be unsure of which one to use or even how each of them work. In this post, we'll go over what
rem are and their differences so that you can pick the one that best suits your needs.
Before posting this blog, I did a little quiz on Twitter. Here are the results from that poll:
Only 12% of people answered with the correct answer. I knew
em confused me, but I didn't realize it confused a lot of other people as well. So let's dive into what
rem are and how they work.
em is a unit that is relative to the font size of the element. If the element doesn't have a specified font size, it will inherit its parent's font size. I like to think of
em as standing for the "element's measurement."
Let's use a button as an example.
In this example, we'll assume the button is inheriting a
16px font size. This would originally make
So far, so good.
When we change the font size of the button to
2em, the element's font size changes from
2em). This also makes sense. The confusing part is what happens to padding. Since the element's new font size is
32px, this makes the button's padding become
32px, or the new value for
Yeah, CSS is wild.
rem, or root
em, is a unit that is relative to the font size of the root (
<html>) element, which is typically
16px. Applying "my version" of what
em stands for to
rem would stand for the "root element's measurement."
rem, changing the element's font size doesn't change the
rem value for other properties. It's always
16px, or whatever the root element's font size is. (Note: it's probably not a good idea to override the
<html> element's font size because the user agent stylesheet sets it. You can learn more about the user agent stylesheet in Jens Oliver Meiert's article, "User Agent Style Sheets: Basics and Samples".)
Let's revisit the example from earlier, but this time, we'll use
In this case, the font size (
32px and the padding (
16px, which is exactly what you'd expect.
So which one should I use?
It depends! If this is something you're concerned about, I recommend doing your own research to see which works best for your purposes.
After doing some research, I prefer
rem so that I don't have to worry about the font size of an element changing to something unexpected, especially if I work in a system that a lot of other developers have touched.