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.
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.
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 (9)
Amazing explanation indeed!
Thanks
So, where's rem inherited to if we don't fill anything (margin, padding, font-size, etc) on html class?
I think most browsers default the body to 16px which is what rem would be set to.
Yes, it has a default of 16px
One of the "clearest" explanations I have seen on this topic.
Glad I could help
What a very nice and interesting write up
Hope we will be expecting more right
Thanks for the explanation π