DEV Community

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

Posted on

15 6

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).

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more