DEV Community

Cover image for CSS Unit: em
Ayu Adiati
Ayu Adiati

Posted on • Updated on • Originally published at adiati.com

CSS Unit: em

Hello Fellow Codenewbies 馃憢

If you've read my previous post, then you've learned that em can cause problems since it creates cascading effect.
That's why we preferably avoid using it for font-size.

So when or where is using em would be good?


Let's create an h1 and a p tag inside a container and set the font-size of the h1 to 3rem with margin-bottom of 1em.

(We will leave the p tag as it is because we only want to focus on the margin-bottom where we apply the em unit).

Now let's change the font-size to 5rem.

h1 {
  font-size: 5rem;
  margin-bottom: 1em;
}
Enter fullscreen mode Exit fullscreen mode

馃憖

When you see the the rendered page, do you notice that the size of margin-bottom is the same as the size of h1's font-size?

But we've set the margin-bottom to 1em. So the size should be 16px since we don't declare font-size anywhere except the h1, right?

馃挕

Beside inherits size from its parent, another thing to know about em is that it is also relative to the font-size of its own element.

So whenever we set a font-size within an element and we set the value of margin or padding inside the same element in em unit, then this margin or padding will be relative to the font-size in the element.

Summary

When we do responsiveness, the use of em in margin or padding would be very handy.

That's because we don't need to change the size of margin or padding whenever we change the font-size.

Discussion (3)

Collapse
zoedreams profile image
鈽笍鉁濓笍鈽笍馃晧鈽革笍鉁★笍鈽笍

there is rem -- relative em too which is awesome

Collapse
adiatiayu profile image
Ayu Adiati Author

Yes! rem is "root" element which is relative to html, the root of he document馃槉

Collapse
phimmoibilutv profile image
Phimmoi hay tr锚n Bilutv.vn