Can u explain the secret of em please?

what does 1em mean? if i don’t set a font size to a parent element then what would be the font size of its child element if i set it to 2em???


You should refer to this but if in case it’s not specified otherwise, 1 em = 16px which is the browser default.

Cheers!

1 Like

Specifically, the (approximate) width of one letter “m”.

In CSS, that means the element’s font-size. More specifically, the font size relative to the parent element’s font size.

Easier with an example:

<h1>The Title <small>& a subtitle</small></h1>
h1 > small {
  font-size: 0.75em;
}

Whatever the font size of h1 is, a small that is child of it will be 0.75× the size. So if the size of the h1 is 20px, then the small will be 15px.

<p> 2<sup>2</sup> is 4</p>
p sup {
  font-size: 0.5em;
}

So a superscript element would be half the font size of the p element that is its parent.

ems are tricky because of the way they are relative. So if you do

p {
  font-size: 1.5em;
}

But if you have a p, then a p then a p, and the parent font size is 16px, that means first one will be 24px, child will be 36px, child will be 54px.

It gets a bit confusing past simple cases. Which is why you generally use rem units, which are always relative to the size of the root element (normally <html>, which is 16px by default), rather than whatever the parent is.

1 Like

You definitely need to keep the unit compounding effect in mind.

Here is an article with a visual example of how it works.

so the parent p elemnet’s font size 1em = 16px by default…right??? i mean the parent element will always get the default font size for 1em…

No, the parent element’s font size is whatever had been set on it. 1em is just 100% of the parent, 2em is twice the parent, 0.5em is half.

1 Like