DEV Community

Cover image for em VS rem
Abdulqudus Abubakre
Abdulqudus Abubakre

Posted on

em VS rem

In the world of CSS and sizing, there are several units that can be used either for your font sizing, margin, padding and so on.

Two commonly used, but slightly confusing units are the rem and em. Both units are relative CSS units (they depend on something else for their sizing). Now how are these two different???

em

This unit inherits the font size of its nearest parent element having a font-size. I'll be going with a visual representation here to explain how the inheritance works.

inheritance in em

In the image above, the root element has a font size of 36px. The body element which is a child of the root element has a font size of 0.8em, which is equivalent to 80% of the font-size of the root element i.e (0.8 * 36px = 28.8), and it goes on and on. If the immediate parent does not have a set font size, it looks for the parent element having a defined font size.

rem

This unit inherits the font size of the root element. You can think of it as the root em. In this case, rather than inheriting the font size of its immediate element, it inherits that of the html element.

inheritance in rem

Here, no matter how deeply nested the element is, it always finds its way home πŸ˜€πŸ˜€....in this case, the root element.

Here's a codepen demo showing em and rem in action.

Conclusion

This a just a look into em and rem, which one you choose is entirely up to you. With em you can have different font sizes for different sections. With rem you have a central controller that you can use to determine sizes of other elements in your html.

Top comments (8)

Collapse
 
rahuldkjain profile image
Rahul Jain

Amazing explanation indeed!

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Thanks

Collapse
 
bayuangora profile image
Bayu Angora • Edited

So, where's rem inherited to if we don't fill anything (margin, padding, font-size, etc) on html class?

Collapse
 
danielatwood profile image
Daniel Atwood

I think most browsers default the body to 16px which is what rem would be set to.

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Yes, it has a default of 16px

Collapse
 
timothyokooboh profile image
timothyokooboh

One of the "clearest" explanations I have seen on this topic.

Collapse
 
ibn_abubakre profile image
Abdulqudus Abubakre

Glad I could help

Collapse
 
yusufsaif profile image
yusuf-saif

What a very nice and interesting write up
Hope we will be expecting more right