There are many choices when it comes to units in CSS. em and rem are very important units used in CSS, especially when it comes to flexibility. I know lots of people use em and rem, but you might be wondering what the difference is between the two. I actually thought rem was the bigger version of em. lol. Let's quickly take a look at the difference between the two: When you set a font-size to em unit it is usually in relation to the element's parent. Take, for instance :
.parent-div{
font-size:16px;
}
.child-div{
font-size:2em;
}
The size of the child element will be 2 times the size of the parent element, which is 2*16px=32px. So the child element is 32px.
That’s quite straight forward, isn’t it? em units can also be used on so many properties such as margin, padding, width, height, etc. But here’s the thing, when you use em on other properties take for instance padding, its size will be relative to the font size of the element itself. Confusing? Let’s take a look
.parent-div{
font-size:16px;
}
.child-div{
Font-size:2em;
Padding:2em;
}
So the padding here will be 2 times the number of the font size of the child element.
Everything has been good so far, but there's an issue that comes with using em especially within nested items. em unit tends to compound the sizes of elements nested together. You can click the link to my codepen below to see the example.
rem is a shorthand for root em, it is more consistent and it always takes the size of the root element which is the <html> element and if this is not set to specified font size, it takes up the browser default font size which is 16px. Take,for instance:
html{
font-size:12px;
}
.parent-div{
font-size:16px;
}
.child-div{
font-size:2em;
}
The child element ignores the value of the parent element and only the value of the root element is considered. rem unit was created to solve the problem of the compounding issue caused by the em unit.
There should be no debate on the best unit to be used because it all depends on what you prefer. If what you're looking for is consistency then you would want to consider using rem.
I hope this article was useful.........