DEV Community

Discussion on: CSS Units: REM or EM!?

Collapse
 
jharteaga profile image
Jose Arteaga • Edited

Facundo gave an excellent explanation, and that's the reasoning. Before, I used to use a lot the px and rem unit, in almost everything, then I realized that using px and rem are almost the same, the difference with rem is that you scale 16px by 16px (if you don't change the default root font size). So instead of setting a margin with 16px, you put 1rem. The problem is scaling, as Facundo mentioned.

For example, If the font-size decreases from 3rem to 2rem, the margin will remain the same using rem because it's looking to the root font-size which is still 16px. Otherwise, if you use em, the margin will change and adapt, because it's relative to its parent font-size.

Let's do the arithmetic, we are going to assume that we haven't changed the default font-size of the root element, which is 16px. So the following values are for the same container:

font-size: 2.5rem => (16px * 2) + (16px / 2) => 40px
margin: 0.5em => 20px (half of the parent font size, 1em = 40px)

If we change the font-size to 2rem, the margin will change automatically to 16px.

So, this is the advantage of using rem in font-size and em in margin and padding, otherwise, you will finish changing always all your values trying to adapt things when font-size change.

Hope this helps guys!

Collapse
 
nickyoung profile image
Nick Young

Thank you for this awesome reply. It totally makes sense now that you have laid it out like that. I am going to start doing this. Thank you!