CSS 为什么是 em 而不是 px?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/609517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why em instead of px?
提问by Spoike
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?
我听说您应该使用 em 而不是像素来定义样式表中的大小和距离。所以问题是为什么在css中定义样式时我应该使用em而不是px?有没有一个很好的例子来说明这一点?
采纳答案by Spoike
The reason I asked this question was that I forgot how to use em's as it was a while I was hacking happily in CSS. People didn't notice that I kept the question general as I wasn't talking about sizing fonts per se. I was more interested in how to define styles on any given block elementon the page.
我问这个问题的原因是我忘记了如何使用 em ,因为有一段时间我在 CSS 中愉快地hack。人们没有注意到我保留了这个问题的一般性,因为我并不是在谈论字体大小本身。我更感兴趣的是如何在页面上的任何给定块元素上定义样式。
As Henrik Pauland others pointed out em is proportional to the font-size used in the element. It's a common practice to define sizes on block elements in px, however, sizing up fonts in browsers usually breaks this design. Resizing fonts is commonly done with the shortcut keys Ctrl++or Ctrl+-. So a good practice is to use em's instead.
正如Henrik Paul和其他人指出的那样,em 与元素中使用的字体大小成正比。在 px 中定义块元素的大小是一种常见的做法,但是,在浏览器中调整字体大小通常会破坏这种设计。调整字体大小通常使用快捷键Ctrl++或Ctrl+ 完成-。所以一个好的做法是使用 em 来代替。
Using px to define the width
使用 px 定义宽度
Here is an illustrating example. Say we have a div-tag that we want to turn into a stylish date box, we may have HTML-code that looks like this:
这是一个说明性的例子。假设我们有一个 div 标签,我们想把它变成一个时尚的日期框,我们可能有这样的 HTML 代码:
<div class="date-box">
<p class="month">July</p>
<p class="day">4</p>
</div>
A simple implementation would defining the width of the date-box
class in px:
一个简单的实现是date-box
用 px定义类的宽度:
* { margin: 0; padding: 0; }
p.month { font-size: 10pt; }
p.day { font-size: 24pt; font-weight: bold; }
div.date-box {
background-color: #DD2222;
font-family: Arial, sans-serif;
color: white;
width: 50px;
}
The problem
问题
However, if we want to size the text up in our browser the design will break. The text will also bleed outside the box which is almost the same what happens with SO's design as flodinpoints out. This is because the box will remain the same size in width as it is locked to 50px
.
但是,如果我们想在浏览器中放大文本的大小,设计就会中断。文本也会在框外流血,这与flodin指出的SO 设计中发生的情况几乎相同。这是因为框的宽度将保持与锁定到 相同的大小50px
。
Using em instead
使用 em 代替
A smarter way is to define the width in ems instead:
更聪明的方法是在 em 中定义宽度:
div.date-box {
background-color: #DD2222;
font-family: Arial, sans-serif;
color: white;
width: 2.5em;
}
* { margin: 0; padding: 0; font-size: 10pt; }
// Initial width of date-box = 10 pt x 2.5 em = 25 pt
// Will also work if you used px instead of pt
That way you have a fluid design on the date-box, i.e. the box will size up together with the text in proportion to the font-size defined for the date-box. In this example, the font-size is defined in *
as 10pt and will size up 2.5 times to that font size. So when you're sizing the fonts in the browser, the box will have 2.5 times the size of that font-size.
这样你就可以在日期框上进行流畅的设计,即框将与文本一起按为日期框定义的字体大小成比例放大。在这个例子中,字体大小被定义*
为 10pt 并且将放大到该字体大小的 2.5 倍。因此,当您在浏览器中调整字体大小时,该框的大小将是该字体大小的 2.5 倍。
回答by thomasrutter
It is wrong to say that one is a better choice than the other (or both wouldn't have been given their own purpose in the spec). It may even be worth noting that StackOverflow makes extensive use of px units. It is not the poor choice Spoike was told it was.
说一个是比另一个更好的选择是错误的(或者两者都不会在规范中给出自己的目的)。甚至可能值得注意的是,StackOverflow 广泛使用了 px 单位。这不是斯波克被告知的糟糕选择。
Definition of units
单位定义
pxis an absolute unit of measurement (like in, pt, or cm) that also happens to be 1/96 of an inunit (more on why later). Because it is an absolute measurement, it may be used any time you want to define something to be a particular size, rather than being proportional to something else like the size of the browser window or the font size.
Like all the other absolute units, pxunits don't scale according to the width of the browser window. Thus, if your entire page design uses absolute units such as pxrather than %, it won't adapt to the width of the browser. This is not inherently good or bad, just a choice that the designer needs to make between adhering to an exact size and being inflexible versus stretching but in the process not adhering to an exact size. It would be typical for a site to have a mix of fixed-size and flexible-sized objects.
Fixed size elements often need to be incorporated into the page - such as advertising banners, logos or icons. This ensures you almost always need at least somepx-based measurements in a design. Images, for example, will (by default) be scaled such that each pixel is 1*px* in size, so if you are designing around an image you'll need pxunits. It is also very useful for precise font sizing, and for border widths, where due to rounding it makes the most sense to use pxunits for the majority of screens.
All absolute measurements are rigidly related to each other; that is, 1inis always96px, just as 1inis always72pt. (Note that 1inis almost never actually a physical inchwhen talking about screen-based media). All absolute measurements assume a nominal screen resolution of 96ppi and a nominal viewing distance of a desktop monitor, and on such a screen one pxwill be equal to one physicalpixel on the screen and one inwill be equal to 96 physical pixels. On screens that differ significantly in either pixel density or viewing distance, or if the user has zoomed the page using the browser's zoom function, pxwill no longer necessarily relate to physical pixels.
emis not an absolute unit - it is a unit that is relative to the currently chosen font size. Unless you have overridden font style by setting your font size with an absolute unit (such as pxor pt), this will be affected by the choice of fonts in the user's browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales.
Use emwhen you specifically want the size of something to depend on the current font size.
%is also a relative unit, in this case, relative to either the height or width of a parent element. They are a good alternative to pxunits for things like the total width of a design if your design does not rely on specific pixel sizes to set its size.
Using %units in your design allows your design to adapt to the width of the screen/device, whereas using an absolute unit such as pxdoes not.
px是绝对测量单位(如in、pt或cm),也恰好是in单位的1/96 (稍后会详细说明原因)。因为它是一个绝对测量值,所以任何时候您都可以使用它来定义特定大小的东西,而不是与浏览器窗口的大小或字体大小等其他东西成比例。
与所有其他绝对单位一样,px单位不会根据浏览器窗口的宽度进行缩放。因此,如果您的整个页面设计使用绝对单位,例如px而不是%,它将无法适应浏览器的宽度。这本身没有好坏之分,只是设计师需要在坚持精确尺寸和不灵活与拉伸但在此过程中不坚持精确尺寸之间做出的选择。一个站点通常混合有固定大小和灵活大小的对象。
固定大小的元素通常需要合并到页面中 - 例如广告横幅、徽标或图标。这确保您几乎总是需要在设计中至少进行一些基于 px 的测量。例如,图像将(默认情况下)缩放为每个像素的大小为 1*px*,因此如果您围绕图像进行设计,则需要px单位。它对于精确的字体大小和边框宽度也非常有用,由于四舍五入,在大多数屏幕上使用px单位是最有意义的。
所有绝对测量值彼此严格相关;也就是说,1英寸是永远96PX,就像1英寸是永远72pt。(请注意,在谈论基于屏幕的媒体时,1in实际上几乎从来都不是物理英寸)。所有绝对测量均假设标称屏幕分辨率为 96ppi 和桌面显示器的标称观看距离,在这样的屏幕上,一像素将等于屏幕上的一个物理像素,一英寸等于将等于 96 个物理像素。在像素密度或观看距离有显着差异的屏幕上,或者如果用户使用浏览器的缩放功能缩放页面,px将不再一定与物理像素相关。
em不是绝对单位 - 它是相对于当前选择的字体大小的单位。除非您通过使用绝对单位(例如px或pt)设置字体大小来覆盖字体样式,否则这将受到用户浏览器或操作系统中字体选择的影响(如果他们已经制作了字体),因此没有意义使用 em 作为一般长度单位,除非您特别希望它随着字体大小的缩放而缩放。
当您特别希望某些内容的大小取决于当前字体大小时,请使用em。
%也是一个相对单位,在这种情况下,相对于父元素的高度或宽度。如果您的设计不依赖特定的像素大小来设置其大小,它们是px单位的一个很好的替代品,例如设计的总宽度。
在您的设计中使用%单位可以让您的设计适应屏幕/设备的宽度,而使用px等绝对单位则不然。
回答by flodin
I have a small laptop with a high resolution and have to run Firefox in 120% text zoom to be able to read without squinting.
我有一台高分辨率的小型笔记本电脑,必须以 120% 的文本缩放比例运行 Firefox,才能在不眯眼的情况下阅读。
Many sites have problems with this. The layout becomes all garbled, text in buttons is cut in half or disappears entirely. Even stackoverflow.com suffers from it:
很多网站都有这个问题。布局变得全乱,按钮中的文本被切成两半或完全消失。甚至 stackoverflow.com 也会受到影响:
Note how the top buttons and the page tabs overlap. If they would have used em units instead of px, there would not have been a problem.
请注意顶部按钮和页面选项卡是如何重叠的。如果他们使用 em 单位而不是 px,就不会有问题。
回答by Vbakke
The top voted answer here from thomasrutter is right in his response about the em. But is very very wrong about the size of a pixel. So even though it is old, I cannot let it be undebated.
thomasrutter 在这里投票最高的答案在他对em 的回应中是正确的。但是关于像素的大小是非常非常错误的。所以即使它很旧,我也不能让它不争论。
A computer screen is normally NOT 96dpi! (Or ppi, if you want to be pedantic.)
电脑屏幕通常不是 96dpi!(或者 ppi,如果你想学究。)
A pixel does NOT have a fixed physical size.
(Yes, it is fixed within onescreen only, but in the next screen a pixel is most likely bigger, or smaller, and certainly NOT 1/96 of an inch.)
Proof
Draw a line, 960 pixels long. Measure it with a physical ruler. Is it 10 inches? No..?
Connect your laptop to your TV. Is the line 10 inches now? Still not?
Show the line on your iPhone. Still same size? Why not?
像素没有固定的物理尺寸。
(是的,它仅在一个屏幕内固定,但在下一个屏幕中,像素很可能更大或更小,当然不是 1/96 英寸。)
校样
画一条 960 像素长的线。用物理尺子测量它。是10英寸吗?不..?
将笔记本电脑连接到电视。这条线现在是 10 英寸吗?还没?
在 iPhone 上显示这条线。还是一样大小?为什么不?
Who the heck invented the 96dpi computer screen myth?
(Some religions operate with a 72dpi myth. But equally wrong.)
到底是谁发明了 96dpi 的电脑屏幕神话?
(一些宗教以 72dpi 的神话运作。但同样错误。)
回答by Daniel Rikowski
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.
它在通过缩放字体大小来实现缩放的浏览器上特别有用。因此,如果您使用em
它们相应地缩放所有元素的大小。
回答by Henrik Paul
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.
因为 em ( http://en.wikipedia.org/wiki/Em_(typography)) 与当前使用的字体大小成正比。如果字体大小是 16 磅,那么 1 em 就是 16 磅。如果您的字体大小为 16 像素(注意:与点不同),则 1 em 为 16 像素。
This leads to two (related) things:
这导致了两个(相关的)事情:
- it's easy to keep proportions, if you choose to edit your font sizes in your CSS later on.
- 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.
- 如果您稍后选择在 CSS 中编辑字体大小,则很容易保持比例。
- 许多浏览器支持自定义字体大小,覆盖您的 CSS。如果您以像素设计所有内容,在这些情况下您的布局可能会中断。但是,如果您使用 em,这些覆盖应该可以缓解这些问题。
回答by Muhammad Usman Ghani
example:
例子:
Code: body{font-size:10px;} //keep at 10 all sizes below correct, change this value and the rest change to be e.g. 1.4 of this value
代码:body{font-size:10px;} //所有尺寸都保持在 10 以下正确,更改此值,其余更改为例如此值的 1.4
1{font-size:1.2em;} //12px
1{font-size:1.2em;} //12px
2{font-size:1.4em;} //14px
2{font-size:1.4em;} //14px
3{font-size:1.6em;} //16px
3{font-size:1.6em;} //16px
4{font-size:1.8em;} //18px
4{font-size:1.8em;} //18px
5{font-size:2em;} //20px
5{font-size:2em;} //20px
…
…
body
身体
1
1
2
2
3
3
4
4
5
5
by changing the value in body the rest change automatically to be a kind of times the base value…
通过更改 body 中的值,其余部分会自动更改为基值的倍数……
10×2=20 10×1.6=16 etc
10×2=20 10×1.6=16 等等
you could have the base value as 8px… so 8×2=16 8×1.6=12.8 //may be rounded by browser
您可以将基值设为 8px... 所以 8×2=16 8×1.6=12.8 // 可能会被浏览器四舍五入
回答by John Topley
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.
一个非常实际的原因是,如果使用 px 指定字体,则 IE 6 不允许您调整字体大小,而如果您使用诸如 em 或百分比之类的相对单位,则可以。不允许用户调整字体大小对可访问性非常不利。虽然它在下降,但仍然有很多 IE 6 用户。
回答by Scott Evernden
use px for precise placement of graphical elements. use em for measurements having to do positioning and spacing around text elements like line-height etc. px is pixel accurate, em can change dynamically with the font in use
使用 px 精确放置图形元素。使用 em 进行测量,必须围绕行高等文本元素进行定位和间距。px 是像素精确的,em 可以随着使用的字体动态变化
回答by Traingamer
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.
使用 em 或百分比的主要原因是允许用户在不破坏设计的情况下更改文本大小。如果您使用 px 中指定的字体进行设计,则如果用户选择text size -large ,它们不会更改大小(在 IE 6 和其他版本中)。这对于有视觉障碍的用户来说是非常糟糕的。
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 CSSor Dan Cederholm's Bulletproof Web Design.
有关此类设计的几个示例和文章(有无数可供选择),请参阅最新一期的 A List Apart: Fluid Grids、较旧的文章How to Size Text in CSS或 Dan Cederholm 的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.
您的图像仍应以 px 大小显示,但通常情况下,将文本大小设为 px 被认为是不好的形式。
As much as I personally despise IE6, it is currently the onlybrowser approved for the bulk of the users in our Fortune 200 company.
尽管我个人很鄙视 IE6,但它目前是我们财富 200 强公司中唯一被大多数用户认可的浏览器。