How does rem differ from em in CSS ?
The em and rem both are CSS font-size units that can be used in CSS document 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
Output: 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)
HTML code: 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.
- 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.
Browser Chrome Opera Safari Firefox Internet Explorer em 1.0 3.5 1.0 1.0 3.0 rem 4.0 20.0 4.1 3.6 9.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.