@adityaphasu
Posted
Hi,
Let me explain rem and em with some examples:
rem
stands for root em which is relative to the root (html) font size. This means that if you set a property in rem, it will be calculated based on the root font size.
For example, say you have a heading in a page if you use rem then it will ba calculated based on the root font size which is set up in the html (mostly by default its 16px but in some cases people can change and specify it to other values as well)
html {
font-size: 16px;
}
h1 {
font-size: 1.5rem; //1.5 times the root size
}
-
In the above code snippet
1.5rem
means1.5*16px = 24px
.In a different scenario say someone set the root font size to be 18px then h1 would be1.5*18px = 27px
. -
em is element em and is relative to the font size of the element itself or its nearest parent that has a font size set. For example, we have a parent element and inside it we have a child element and we set font sizes to both in em then:
html {
font-size: 16px; // default
}
parent {
font-size: 1.5em; // 1.5 times the parent's font size (1.5 * 16px = 24px)
}
child {
font-size: 1.2em; // 1.2 times the parent's font size
}
- In the code snippet the parent itself has a parent which is the html so the font size for the parent would be 1.5 times the html font size but child's parent is not html instead it's the parent font size (which now is 24px) and hence since em is inherited and based on parent size it would result in 1.2 times 24px (1.2 * 24px).
Therefore use rem
when you want consistent sizing across the page and use em
for when you want sizes to be relative to the font size of a particular element example button paddings.
I hope this gives you somewhat of an idea of how to use it. If you wanna read about more and their differences check this out!
Keep up the hard work and happy coding!🕺🏻
Marked as helpful
@iamdylanmj
Posted
great explanation, thanks a lot@adityaphasu