How does rem differ from em in CSS ?
In this article, we will learn about rem & em in CSS, how they differs from each other. The em and rem are the relative length CSS font-size units that can be used in CSS documents to make a specific element’s font size relative to its parents.
The em is a CSS font-size unit relative to its directly linked parent, rem is in relation with the font-size of the root element which is basically the HTML element.
There are lots of other CSS Units available as well. Let us understand the difference between em and rem with the help of a suitable example.
em CSS Units: The em unit is relative to its parent’s size.
- 1 em = size of parent
- 2 em = twice the size of the parent
- 0.5em = half the size of the parent
Example: This example demonstrates the use of the CSS em unit that specifies the font-size relative to the direct or its parent element.
Explanation: As the elements get nested into one another, the relative size of elements keeps on growing exponentially at a rate of 2x in the above example.
In this example, the child has a relative size of 2em (2x the font size of a parent) with respect to the parent which in turn is 2em (2x parent element’s parent) w.r.t. grandparent and is now 4 times the size of the grandparent.
- Base Element (GreatGrandParent)’s Size: 15px
- GrandParent1,2 Size: 30px
- Parent 1,2 Size: 60px
- Child 1,2 Size: 120px
- GrandChild 1,2: 240px
rem CSS Units: The rem unit is relative to its base root parent element’s size.
- 1 rem = size of root parent (HTML element)
- 2 rem = twice the size of root parent (HTML element)
- 0.5r em = half the size of root parent (HTML element)
In this case, as the elements get nested into one another the relative size of elements remains constant as every element’s size is proportional to the root HTML element and not its direct parent and hence properties are not transferred lower down to children and grandchildren elements.
In this particular example, the parent has a relative size of 2rem (2x the font size of the root HTML element) w.r.t. root element which is the same as its child and its grandchild element and hence the size even after nesting at multiple levels remains constant.
Example: This example demonstrates the use of the CSS rem unit that specifies the font-size relative to the root element.
- Base( GreatGrandParent)’s Font Size : 15px
- GrandParent1,2/Parent1,2/Child1,2/GrandChild1,2 Font Size = 30px
Note: Please notice the output of both the above examples to know the difference.
Advantages of using rem over em:
- While scaling our application to responsive layout using media query functionality, we can directly alter the base font-size of the root element and every child can directly scale altogether with just one media query on the root element.
- When the user has altered the default base font-size of any browser, our application scales well in this case with the usage of CSS rem units.