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;
}
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
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
}
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
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)