em VS rem

Abdulqudus Abubakre - May 23 '20 - - Dev Community

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.

. . . . . . . . . . . . . . . . . .