CSS Unit: em

CSS Unit: em

Subscribe to my newsletter and never miss my upcoming articles

Hello Fellow Codenewbies 👋

If you've read my previous post, then you've learned also 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;
}

👀

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 parents, another thing to know about em is that it is 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.

 
Share this