There are two important relative units in CSS called, em and rem.
em
It is a sizing unit. It works w.r.t parent node/div.
1em is generally 16px (pixels).
Example:
<div class="parent">
<div class="child">
<div class="second_child">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam cumque ratione provident totam soluta, fugiat obcaecati sequi incidunt magnam esse architecto officia, enim tempore minima asperiores? Labore ab error dolores, numquam, quas magnam atque commodi doloribus aperiam maxime consequatur temporibus eos.
</div>
</div>
</div>
CSS -
.parent {
font-size: 16px;
}
.child {
font-size: 2em;
}
.second_child {
font-size: 3em;
}
Suppose the font size of a parent div is set as 16px and the font size of a child div is set as 2em. This generally means that the text inside child div will have font size of 16*2
px i.e 32px.
Now, let's assume that we have set the font size of a second child as 3em, this means that the text content inside second_child will have font size of 16*2*3
px i.e 96px.
In this scenario, when we use em as a unit to define font size then the size is defined w.r.t the parent node. This is called as compounding in CSS.
If there isn't any parent div then 1em will be considered as 16px only.
Codepen -
rem
rem stands for root em. It solves compounding problem of em. rem doesn't work w.r.t parent node instead it always works w.r.t root node i.e html or ::root.
rem is more consistent than em.
For consistent spacing, margin, padding and font-size always use rem.
Example:
::root {
font-size: 16px;
}
or
html {
font-size: 16px;
}
.parent {
font-size: 50px;
}
.child {
font-size: 2rem;
}
.second_child {
font-size: 3rem;
}
In the above example, the font size of a child div is set to 2rem which is 32px in case of rem because we have defined font size as 16px in root. rem unit isn't dependent upon parent instead it works w.r.t the root or html node.
Here, in root we have defined the font size as 16px hence font size of a child div is 16*2
px i.e 32px. Similarly, the font size of a second_child will be 16*3
px i.e 48px.
The parent div does not influence anything inside children divs in case of rem units.
Codepen -
Helpful tip - While defining a font size avoid using em as much as possible. Use it only when it is necessary. To maintain the consistency, use rem unit.
Top comments (2)
I would go so far and say don't use rem units either. What happens when the clients asks for a certain text to have exactly 13px, or he wants to increase the font size by 1px. There's too much math for too little gain.
I stick to pixels across the board, in my design stack and also in css, javascript. This way I have consistency.
Yes, I agree. I use rem only because it scales automatically otherwise pixel is fine. Thank you for your valuable response.