3

I'm trying to convert all of my site's margin values to em in place of pixels, but I'm having a hard time trying to figure out what 'em' actually is. I thought it was a set distance based on the users browser settings (default font-size), but a standard 1em is different when applied to h1 or ul for example. Any help?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jake
  • 1,137
  • 3
  • 11
  • 14

3 Answers3

3

An em is based on the font size (the widthheight of a capital M), so it is a relative measurement, based on whatever font size applies to the element.

See the results of this markup on jsfiddle:

<div style="font-size:2em">2em<div style="font-size:2em">2em</div></div>
<div style="font-size:14px">2em<div style="font-size:2em">2em</div></div>
bdukes
  • 152,002
  • 23
  • 148
  • 175
  • So how would I make a h1 margin and a p margin the same difference (using em)? Thanks – Jake Mar 28 '11 at 20:48
  • Is it relative to the width of the `M` *within* the element? So `font-size` of the element, increases it's width/height? – Blender Mar 28 '11 at 20:48
  • @jake, you don't unless the h1 and the p are exactly the same font-family, font-size and font-weight (and even if you could approximate them the users setting may be different from your suggested CSS!) the Capital "m" of the heading or paragraph is 1em .. if you want exact measurements you use pixels – clairesuzy Mar 28 '11 at 22:17
  • @Blender, yes it does as does font-family, and there could also then be inheritance to factor in.. not every h2 might be the same actual width once it inherits, even though it's been given the same em width - em's and percentages can really be a nightmare once you start adding in plugged in code and they inherit more than you'd like ;) – clairesuzy Mar 28 '11 at 22:22
0

"1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses"

http://www.w3schools.com/css/css_units.asp

Phillip Benages
  • 661
  • 2
  • 9
  • 20
  • 2
    http://w3fools.com/ (let's avoid referencing w3schools). How about http://reference.sitepoint.com/css/lengthunits? – bdukes Mar 28 '11 at 20:49
0

Stackoverflow relevant EPIC answer here: Is sizing fonts using "em" still relevant?

The em measure type will depend on the circumstances (the element parent, the element type / element css properties), read a complete and comprehensive explanation on this here:

http://jontangerine.com/log/2007/09/the-incredible-em-and-elastic-layouts-with-css

Community
  • 1
  • 1
amosrivera
  • 26,114
  • 9
  • 67
  • 76