DEV Community

Mạnh Đạt
Mạnh Đạt

Posted on

em vs rem in CSS Font Size

em

Take this HTML as an example:

<div id="outer">
    <h1 class="heading">Outer heading</h1>

    <div id="inner">
        <h1 class="heading">Inner heading</h1>
    </div>
</div>

Enter fullscreen mode Exit fullscreen mode

And the following CSS:

#outer { font-size: 30px; }
#inner { font-size: 20px; }
.heading { font-size: 3em; }
Enter fullscreen mode Exit fullscreen mode

This is the result:

em font size

If you inspect the headings in dev tools, switch to computed tab, the outer heading has font size 90px and the inner has 60.

That's because em based on its parent's font size.
If I didn't specify a font size for #inner, the two heading would have the same size.

rem

rem is a little bit different. Let's change the .heading font size unit from em to rem:

.heading { font-size: 3rem; }
Enter fullscreen mode Exit fullscreen mode

The two headings now have the same size:
rem

rem doesn't base on the element's parent font size. It based on the root element's font size, which is the html element.

If you don't specify a font size for html, the default value is 16px in m any browsers.

As I inspected the headings in dev tools, switched to computed tab, font size of the headings is 48 (16 * 3).

Top comments (2)

Collapse
 
matthias profile image
Matthias 🤖

If you want to learn about other units in CSS. I shamelessly link to an article I wrote a while ago 😅

Collapse
 
sbateswar profile image
Stanley Bateswar

Honestly this article is the best explanation about understanding em/rem. Thank you!