DEV Community

C.OG
C.OG

Posted on

Sizing Units in CSS: REM and EM

CSS has different units for expressing length. Many units take a length property, such as: font-size, padding, width etc. There are two types of length units: absolute and relative.

This article focuses on two relative units: REM and EM. We discuss how the browser converts these into absolute units.

REM to PX

The browser uses the root element's (html) font size as the multiplier when converting to pixels.

html {
  font-size: 16px;
}

h1 {
  font-size: 1rem; 
}
Enter fullscreen mode Exit fullscreen mode

In this example, the font-size of the h1 will be 16px.

The calculation the browser runs:

# root font size * property rem unit = px value
            16px * 1rem              = 16px
Enter fullscreen mode Exit fullscreen mode

EM to PX

The browser uses the font-size of the element that is being styled as the multiplier when converting to pixels. It will bubble up until it gets the first explicit font-size definition.

html {
  font-size: 16px;
}

div {
  font-size: 22px;
}

div h1 {
  font-size: 2em
}
Enter fullscreen mode Exit fullscreen mode

In this example, the font-size of the h1 will be 44px.

The calculation the browser runs:

# element font size * property em unit = px value
               22px * 2em              = 44px

Enter fullscreen mode Exit fullscreen mode

In this scenario, the element font size is inherited from the parent div

It's important to remember that font-size inheritance will come into effect if no font-size is explicitly set. For rem, if there is no font-size explicitly set on the root element, it will inherit the value from the browser settings.

Top comments (0)