[CSS] Understanding em & rem in CSS

[CSS] Understanding em & rem in CSS

Introduction

In this article, I will talk about em & rem units in CSS and explain when we can use those units to make better web pages.


em (relative to parent)

em is a unit used for font size, but the size of a font is relative to the parent.

HTML:

<div>
    <p>The font size is 12 * 2 = 24px</p>
</div>

CSS:

div {
    font-size: 12px;
}
p {
    font-size: 2em
}

The font size of <p> is 24px because the parent of <p>, which is <div> has a font size of 12px. Therefore, 2em means 2 * 12px = 24px.

But, there is a disadvantage when using an em unit. Your code can be more complicated as parents get more and more.


rem (relative to root element)

rem is also a unit used for font size, but the size of a font is relative to the root element.

To simply put it:

The font size is dependent on the <html> element's font size.

By default, html body has a font size of 16px.

HTML:

<div>
    <p>The font size is 16 * 0.5 = 8px</p>
</div>

CSS:

p {
    font-size: 0.5rem;
}

Let's have a look at another example.

<div>
    <p>The font size is 8 * 1.5 = 12px</p>
</div>

CSS:

html {
    font-size: 8px;
}

div {
    font-size: 1.5rem;
}

Use of rem in real life:

Nowadays, some web pages allow users to choose the font size like small, medium or large.

If you use rem on each element that will be visible on the page, your website will then be able to change the font size based on the user's preference.

If the users want a large font size, the website can display 2 rem. If small, the website can display 1 rem.


Reference

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units

Did you find this article valuable?

Support Lim Woojae by becoming a sponsor. Any amount is appreciated!