CSS中的字体大小-%还是em?
时间:2020-03-06 14:42:55 来源:igfitidea点击:
在CSS中设置字体大小时,我应该使用百分比值(%)还是em?我们能解释一下优势吗?
解决方案
从http://archivist.incutio.com/viewlist/css-discuss/1408
%: Some browsers doesn't handle percent for font-size but interprets 150% as 150px. (Some NN4 versions, for instance.) IE also has problems with percent on nested elements. It seems IE uses percent relative to viewport instead of relative to parent element. Yet another problem (though correct according to the W3C specs), in Moz/Ns6, you can't use percent relative to elements with no specified height/width. em: Sometimes browsers use the wrong reference size, but of the relative units it's the one with least problems. You might find it interpreted as px sometimes though. pt: Differs greatly between resolutions, and should not be used for display. It's quite safe for print use though. px: The only reliable absolute unit on screen. It might be wrongly interpreted in print though, as one point usually consist of several pixels, and thus everything becomes ridiculously small.
两者都根据字体大小调整字体大小。 1.5em与150%相同。唯一的好处似乎是可读性,选择最适合一个。
在A List Apart上有一篇关于Web版式的非常好的文章。
他们的结论是:
Sizing text and line-height in ems, with a percentage specified on the body (and an optional caveat for Safari 2), was shown to provide accurate, resizable text across all browsers in common use today. This is a technique you can put in your kit bag and use as a best practice for sizing text in CSS that satisfies both designers and readers.
正如Galwegian所说,px是最可靠的Web版式,因为我们在页面上所做的所有其他操作大部分都是参考计算机监视器来进行布局的。绝对大小的问题在于某些浏览器(IE)无法缩放网页上的像素值元素,因此,当我们尝试放大/缩小时,除那些元素外,所有内容都会调整。
我不知道IE8是否可以正确处理此问题,但是所有其他浏览器供应商都可以很好地处理像素,这仍然是少数情况,用户需要放大/缩小文本(SO上的此文本框可能是例外)。如果我们真的想弄脏,可以随时添加一个javascript函数以使文本大小变大,并为用户提供一个"小" /"大"按钮。
Yahoo用户界面库(http://developer.yahoo.com/yui/)具有一组不错的基础CSS类,用于"重置"浏览器特定的设置,以便所有显示站点的基础都是相同的(受支持)浏览器。
对于YUI,应该使用百分比。
鉴于(几乎?)所有浏览器现在都可以调整整个页面的大小,而不仅仅是调整文本的大小,以前关于px和vs%相对于em的问题在可调整字体大小方面是没有意义的。
因此,答案是可能无关紧要。使用对我们有用的任何东西。
% is nice because it allows for relative resizing. px is nice because it's fairly easy to manage expectations when using it. em can be useful when also used for layout elements as it can allow for proportional sizing related to the text size.