EM or REM? Scaling with font size
This may be an old trick, but we'll go through some tips when to use rem and em to ease your life as a frontend engineer.
EM or REM?
TL;DR
- Use only
em
forfont-size
. - Use
em
formargin
orpadding
if it scales withfont-size
. - Use
rem
formargin
orpadding
otherwise.
EM all the way for font-size
!
em
scales based on the closest font-size
. By default, the font-size
of the html
element for browsers is 16px. With this, let’s see the below example on how em
inherits the values.
Two things to notice here.
-
The
<p>
element with 24px has itsfont-size
inherited from its parent which is 1.5em. The<p>
element with 36px again has afont-size
of 1.5em, but this time its value is based off its parent’sfont-size
which has already be computed as 24px. -
The
.container
element has itsmargin
andpadding
set to1em
. The image below shows the box model of the element. Notice that themargin
andpadding
are computed as 24px instead of 16px, due to the fact thatem
scales relatively to the closestfont-size
.
When to use REM?
Now that we have understood the effects of inheritance using em, there will be situations where it backstabs you.
rem to the rescue! rem aka Root EM calculated its value using the root font-size
which is set at html
, or 16px by default. This is useful when you don’t want your sizes to be scale off the closest font-size
.
Another situtation where I find rem
useful is when I’m implementing Material Design. In MD, many of the keylines are in rhythm of 8dp, which is 0.5rem on default browser behaviour. I can easily add 0.5rem to achieve the look and feel that I wanted (not that I can’t do multiplies of 8 😝).
To recite
- Use only em on
font-size
. - If you want to scale with
font-size
, example, to increase spaces around a text when thefont-size
increases, use em. - Use rem otherwise.