REM and EM units in CSS often create confusion for beginners. Most beginners don't understand the correct meaning of both units and use both without fully understanding them leading to issues in their codebase down the line.
REM and EM are known as relative units in CSS. You've probably been using REM and EM units now for a while already, but you might still be confused about which unit is best in which scenario.
An em value is equal to the computed font-size of the parent of that element. For example, if the font size of the parent element is 20 px then 1em is equal to 20px.
If the font size is not specified in the parent element, then it will continue to look up until the root element.
The root element’s font size is provided by the browser and by default it is 16px. In this case, 1em is equal to 16px.
Check the challenge below, then skip ahead to the answer to understand how em works.
https://twitter.com/Ali6nX404/status/1445427836320247810?s=20
We have three divs; Container, Parent, and Child with font sizes of 1em, 3em, and 2em respectively.
The final size of the child becomes 96px. This is the power of compounding 😅.
See a live example 👇
https://codepen.io/ali6nx404/pen/QWMLWWm
Let's see this in action 👇
While em is relative to the font size of its direct or nearest parent, rem is only relative to the HTML (root) font size. By default, this is 16px unless we specify it in the HTML element. The rem value is not very convenient when it comes to specifying such as 1rem = 16px,
But what do we do if we want to use 10px? Then we need to calculate the rem value which is equal to 0.625rem.
To solve this problem, we have one trick; specify the HTML element font size as 62.5%. Then, our 1rem becomes 10px and now we are able to calculate size easily.
There’s no better unit really, and it all depends on your personal choice. Some people like to use rem units for consistency and scalability, while some like to use em units in places where the influence of nearby parent elements would make sense.
I personally use rem more than em but be careful with both, em becomes a bit of trouble when you don't understand the relation between parents and child, and above we already saw the example of the compounding effect of em. I prefer to use rem more often than em.
Trying out both units and understanding their use cases is the most important thing. I would suggest that you play with both units and understand both of them.