CSS Length Units

Relative to font size

The em length unit is a relative length unit where the base length is calculated from the width of the character M of the current element. We often use the fact that the font-size property is inherited by child elements to correctly scale elements according to the surrounding context.

Using em units can become confusing when we nest them several layers deep since they work as multipliers.

When to use em

We mainly use em for positioning, spacing and size purposes when we want to allow for reliable scalability within a surrounding context. We will later on see that em comes in extremely handy when writing re-usable components.

Code example

<style>
#blue-box {
width: 250px;
height: 250px;
background-color: blue,
color: white;
/* 1.0em == 16px */
font-size: 16px;
}
#red-box {
background-color: red,
color: black;
/* 1.0em == 16px (inherited from parent) */
font-size: 1.5em;
padding: 0.25em;
}
</style>
<div id="blue-box">
I am a blue box with a font size of 16px
<div id="red-box">
I am a red box with a font size of 1.5 x 16px = 24px,
and a padding of 0.25 * 16px = 4px
</div>
</div>

which produces

I am a blue box with a font size of 16px
I am a red box with a font size of 1.5 x 16px = 24px, and a padding of 0.25 * 16px = 4px

Code example: confusing

<style>
h1 {
font-size: 1em;
padding: 2em;
}
h2 {
font-size: 2em;
padding: 2em;
}
</style>
<h1>Main header</h1>
<h2>Sub header</h2>

The <h1> and <h2> elements are direct children of the main <body> element. Most people would expect the padding of <h1> and <h2> to be the same absolute length, but that is not true. Remember that em uses the current element's font size as a basis. The rest of the attributes are calculated after the font size has been set.

What this means for this example is that the <h2> element has 4 times the padding of the <h1> element. All major web browsers set the font size of the <html> and <body> tag to 16px. So converted to absolute units the same styling can be written as

h1 {
font-size: 16px; /* 1.0em == 16px */
padding: 32px; /* 2.0em == 32px */
}
h2 {
font-size: 32px; /* 2.0em == 32px */
padding: 64px; /* 2.0em == 64px */
}

Test yourself

Description

Change the font-size of the <nav> element to

18px

All of the rules are defined for you. You only need to modify the correct declarations.

Pay attention to how the list elements' font size, padding, margin, and border widths scale when we change the font size of the <nav> element.

Tests

  1. 1 Your nav element should have the font size 18px.
Editor
Preview