What is the em font-size unit? How much is it in pixels?

前端 未结 8 1120
孤独总比滥情好
孤独总比滥情好 2020-12-02 12:30

I want to know what the em unit is, and how much 1em is when converted to pixels (px). I also read somewhere about some IE bug, to overcome which b

相关标签:
8条回答
  • 2020-12-02 13:09

    It's calculated off of whatever your body font size is. You can use a pixel to em converter to find out exactly what it is on your site.

    PxToEm

    0 讨论(0)
  • 2020-12-02 13:10

    The M-principle that an em is based on the letter M and is dependent on font is an often stated myth!! W3c em documentation very succinctly describes exactly how ems and pixels relate. Using the letter M to compute font-sizes is at the very least overly complicated and unnecessary.

    The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element. It may be used for vertical or horizontal measurement.

    Here are the salient points.

    1. Without ancestor magnification, 1em is exactly equal to the pixel font-size attribute.

    2. Ancestor magnification with x-ems or x-percent means you just multiply by the obvious ratios x or x/100. Thus a simple java-script loop will calculate exact font sizes, assuming: (1) no C.S.S to frustrate java-script; and (2) some ancestor has it's font size set in absolute units. This is the computed value the documentation is talking about. A hand calculation can get around C.S.S., but an absolute unit must still be found in the ancestor chain.

    3. Since ems measure width you can always compute the exact font size by creating a div that is 1000 ems long and dividing its client-Width property by 1000. Since ems are rounded to the nearest thousandth you need 1000 ems to avoid erroneous pixel truncation.

    4. You probably can create a font where the M-principle fails since em is based on the font-size attribute not on the actual font. Suppose you have a weird font where M is 1/3 the size of the other characters and you have a font size of 10 pixels. Don't you think the pixel font-size guarantees maximal character height in some way and so the M will not be 10 pixels and all other characters 30 pixels?

    Warning

    1. A major caveat to (2) is that the relative ratio of the ex unit is wildly unstable. In the same browser with constant font, the relative ratio can change with font size. The relative ratio of ex also changes with the browser even with the same font size and browser safe font such as Georgia. This is a pretty good reason not to ever use the ex unit if you want conformity. If the ex unit is used, it is impossible to compute the font-size through the ancestor chain.
    0 讨论(0)
提交回复
热议问题