EM or REM?
- Use only
paddingif it scales with
EM all the way for
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.
<p>element with 24px has its
font-sizeinherited from its parent which is 1.5em. The
<p>element with 36px again has a
font-sizeof 1.5em, but this time its value is based off its parent’s
font-sizewhich has already be computed as 24px.
.containerelement has its
1em. The image below shows the box model of the element. Notice that the
paddingare computed as 24px instead of 16px, due to the fact that
emscales relatively to the closest
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
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 😝).
- Use only em on
- If you want to scale with
font-size, example, to increase spaces around a text when the
font-sizeincreases, use em.
- Use rem otherwise.