Why em instead of px?

后端 未结 15 1041
闹比i
闹比i 2020-11-22 06:38

I heard you should define sizes and distances in your stylesheet with em instead of in pixels. So the question is why should I use em instead of px when defining styles in c

相关标签:
15条回答
  • 2020-11-22 07:32

    Because the em (http://en.wikipedia.org/wiki/Em_(typography)) is directly proportional to the font size currently in use. If the font size is, say, 16 points, one em is 16 points. If your font size is 16 pixels (note: not the same as points), one em is 16 pixels.

    This leads to two (related) things:

    1. it's easy to keep proportions, if you choose to edit your font sizes in your CSS later on.
    2. Many browsers support custom font sizes, overriding your CSS. If you design everything in pixels, your layout might break in these cases. But, if you use ems, these overridings should mitigate these problems.
    0 讨论(0)
  • 2020-11-22 07:32

    There is a simple solution if you want to use px to specify font size, but still want the usability that em's provide by placing this in your CSS file:

    body {
      font-size: 62.5%;
    }
    

    Now specify you p (and other) tags like this:

    p {
      font-size: 0.8em; /* This is equal to 8px */
      font-size: 1.0em; /* This is equal to 10px */
      font-size: 1.2em; /* This is equal to 12px */
      font-size: 2.0em; /* This is equal to 20px */
    }
    

    And so on.

    0 讨论(0)
  • 2020-11-22 07:38

    It's of use for everything that has to scale according to the font size.

    It's especially useful on browsers which implement zoom by scaling the font size. So if you size all your elements using em they scale accordingly.

    0 讨论(0)
提交回复
热议问题