Why em instead of px?

2018-12-31 09:58发布

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 css? Is there a good example that illustrates this?

14条回答
大哥的爱人
2楼-- · 2018-12-31 10:21

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.

查看更多
不流泪的眼
3楼-- · 2018-12-31 10:22

You probably want to use em for font sizes until IE6 is gone (from your site). Px will be alright when page zooming (as opposed to text zooming) becomes the standard behaviour.

Traingamer already provided the neccessary links.

查看更多
公子世无双
4楼-- · 2018-12-31 10:25

The general consensus is to use percentages for font sizing, because it's more consistent across browsers/platforms.

It's funny though, I always used to use pt for font sizing and I assumed all sites used that. You don't normally use px sizes in other apps (eg Word). I guess it's because they're for printing - but the size is the same in a web browser as in Word...

查看更多
看风景的人
5楼-- · 2018-12-31 10:26

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.

查看更多
几人难应
6楼-- · 2018-12-31 10:29

The main reason for using em or percentages is to allow the user to change the text size without breaking the design. If you design with fonts specified in px, they do not change size (in IE 6 and others) if the user chooses text size - larger. This is very bad for users with visual handicaps.

For several examples of and articles on designs like this (there are a myriad to choose from), see the latest issue of A List Apart: Fluid Grids, the older article How to Size Text in CSS or Dan Cederholm's Bulletproof Web Design.

Your images should still be displayed with px sizes, but, in general, it is not considered good form to size your text with px.

As much as I personally despise IE6, it is currently the only browser approved for the bulk of the users in our Fortune 200 company.

查看更多
余欢
7楼-- · 2018-12-31 10:31

A very practical reason is that IE 6 doesn't let you resize the font if it's specified using px, whereas it does if you use a relative unit such as em or percentages. Not allowing the user to resize the font is very bad for accessibility. Although it's in decline, there are still a lot of IE 6 users out there.

查看更多
登录 后发表回答