How does rem differ from em in CSS?

In website source, I have sometimes seen developers use the rem unit. Is it similar to em? I tried it to see what it actually does, but what is it relative to?

Demo

HTML

<div>Hello <p>World</p></div>

CSS

div {
    font-size: 1.4rem;
}

div p {
    font-size: 1.4rem;
}

EMs are relative to their parent's font size

REMs are relative to a base font-size

This is important when intermediate containers change font sizes. Child elements with EMs will be affected, those using REMs will not.


The unit rem (root em) stands for the font size of the root element. In an HTML document, the root element is the html element.


While em is relative to the font-size of its direct or nearest parent, rem is only relative to the html (root) font-size.

em gives the ability to control an area of a design. As in, scale the type in that specific area relatively. rem gives the ability to scale type across the entire page easily.


Basically em is relative to the nearest parent in CSS, while is rem is relative to the parent of the page which is usually the html tag...

You see the difference clearly if you run the css below and how the parent is effecting it:

html {
  font-size: 16px;
}

.lg-font {
  font-size: 30px;
}

p.rem {
  font-size: 1rem;
}

p.em {
  font-size: 1em;
}
<div class="lg-font">
  <p class="em">Hello World - em</p>
</div>

<div class="lg-font">
  <p class="rem">Hello World - rem</p>
</div>

Summary:

  • rem : a CSS unit which is relative to the font size of the html element.
  • em : a CSS unit which is relative to the font size of the parent element.

Example:

.element {
  width: 10rem;
  height: 10rem;
  background-color: green;
  font-size: 5px;
}

.innerElement {
  width: 10em;
  height: 10em;
  background-color: blue;
}
<div class="element">
  <div class="innerElement"></div>
</div>

In the above example the green square is 160px by 160 px (unless you don't have browser default at 16px). This is because the browser default of the html element font-size is 16px and 10rem * 16px = 160.

The inside square is 10em big. Because its parent element is 5px the square is 5em * 10px = 50px.

How is this usefull:

By setting all units to rem have the following advantages:

  • We can scale our whole application with one CSS media query, in this media query we can specify the font size. By altering the font size all the elements which have the unit rem will scale accordingly.
  • When users are not using the default browser font-size of 16px our application will scale with the selected font size of the user.