It’s all relative!

This article, part of the writing collection, was published on .

What’s the deal with relative units? Let’s find out.

You can think of em as a multiplier of the font-size you would get from inherit, i.e. this element’s parent.

And you can think of rem as a multiplier of the font-size of the root element, i.e. the html element.

To illustrate, let’s look at this example snippet of HTML:

<html>
<body>
<parent>
<element>

As we look at each element here, we can notice where things change as we dive into the <body> element:

1em = 1rem =
<body> 1 × <html> 1 × <html>
<parent> 1 × <body> 1 × <html>
<element> 1 × <parent> 1 × <html>

Full tree

When we use parent-relative units like em or smaller, elements can reach back up the HTML tree towards the <html> element in order to build a font-size that is relative to its parent, its parent’s parent, and so on, up to the root element. This allows us to have font sizes that scale predictably from a uniform base and allows changes at a given level to cascade down the tree to influence the use of deeper parent-relative units.

body {
font-size: clamp(1em, 0.75em + 0.8vw, 1.25em);
}
element {
font-size: 1.5em;
}
  1. <body> has a font-size of clamp(…),
    which equals clamp(…) × <html>'s font-size
  2. <parent> has a font-size of 1em by default,
    which equals 1 × <body>'s font-size
  3. <element> has a font-size of 1.5em,
    which equals 1 × <parent>'s font-size

That means <element>'s font-size equals:

1.5 × <parent> × <body> × <html>
=
1.5 × 1 × clamp(1em, 0.75em + 0.8vw, 1.25em) × 1rem
=
between 1.5rem and 1.875rem @ 500–1000px browser width
calculated value
<body> 1rem1.25rem
<parent> 1rem1.25rem
<element> 1.5rem1.875rem

Broken tree

However, if <parent> has a non-relative font-size set:

body {
font-size: clamp(1em, 0.75em + 0.8vw, 1.25em);
}
parent {
font-size: 30px;
}
element {
font-size: 1.5em;
}

What’s different here?

<parent> has a font-size of 30px, breaking the chain up the tree to <body> and <html>, i.e. using parent-relative units on a child element (or deeper) of <parent> no longer refers back up the HTML tree.

This means <element>'s font-size equals:

1.5 × <parent>
=
1.5 × 30px
=
45px
calculated value
<body> 1rem1.25rem
<parent> 30px
<element> 45px

You’re in control

Ultimately, how you choose to structure your CSS is up to you. I enjoy embracing the cascade and building on the responsive nature of relative and parent-relative units. Let me know if you have a different way of thinking about this concept or a different way to utilise units in CSS! You can learn more about absolute and relative units on MDN.

1 Response

  1. ❤️ 1 Like