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, you've also 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 can we use em?


An Example

Let's create:

  • An h1 and a p tag inside a container.
  • Set the font-size of the h1 to 3rem
  • Give margin-bottom of 1em to the h1.

We will not set anything to the p tag because we only want to focus on the margin-bottom where we apply the em unit.

Click on the CSS button on Codepen to see the code.

Let's tweak it

Now change the font-size to 5rem.

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

When you see 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?

💡 The Answer

Beside inheriting size from its parents, another thing to know about em is that it is relative to the font-size of its element.
Say we set a font-size for an element. And then set the value of margin or padding for the same element in em. This margin or padding will be relative to the font-size of the element.

Summary

When we do responsiveness, the use of em in margin or padding would be convenient.
That's because we don't need to change the size of the margin or padding whenever we change the font-size.


Thank you for reading!
Last, you can find me on Twitter. Let's connect! 😊

Top comments (2)

Collapse
 
adiatiayu profile image
Ayu Adiati

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