18

When 1em is applied to an element, it takes the default value of the browser (usually, 16px) or the font-size value of its parent, right?. But I noticed that if I use something like margin-top: 1em in a h1 element (without using a reset stylesheet, and therefore, h1 is set to font-size: 32px), then 1em is equal to 32px, even if its parent element is set to font-size: 16px.

However, using something like font-size: 100%; solves the discrepancy.

What am I missing?

TylerH
  • 20,799
  • 66
  • 75
  • 101
r_31415
  • 8,752
  • 17
  • 74
  • 121

2 Answers2

16

When 1em is applied to an element, it takes the default value of the browser (usually, 16px) or the font-size value of its parent, right?

No, it takes its own font-size, computed based on its parent (or the default browser-supplied value). Since the browser-supplied font-size of h1 is 32 pixels, the resultant margin is 32 pixels.

However, using something like font-size: 100%; solves the discrepancy.

By setting font-size: 100%; or font-size: 1em; on an element, you're telling it to use 100% of the font size of its parent, so setting 1em as a length on anything else will follow that 100%.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Oh, well, then it's based on its inherited value. That explains it! – r_31415 Feb 28 '12 at 22:51
  • 3
    It's based on its computed value, rather than its inherited value. There's a subtle difference :) – BoltClock Feb 28 '12 at 22:56
  • @BoltClock can you expand on this a little further please? I had a similar understanding that em is calculated based on the browser default font size of 16 pixels. Citations to W3 would be great too. – Robert Feb 12 '17 at 03:25
  • @Robert Rocha: The em unit is relative to the element's font-size, unless you are specifying font-size itself, in which case it's based on its parent's font-size. The browser default for h1 is 2em, which changes depending on its parent but if you have an HTML document containing nothing but an h1 element, the default sizes of body and html are 16px making h1 32px. If your h1 were in a div with font-size: 2em, this 2em would be doubled and the size would be 64px. – BoltClock Feb 12 '17 at 04:45
11

1em is equal to the font-size of the element in question. So when using it with margins, it will be equivalent to the font-size of the element you're applying the margin too.

animuson
  • 53,861
  • 28
  • 137
  • 147