问题
I have read a lot of articles on this topic (and searched for Q&A), and I have found, but I still don't understand what the difference between em units and percents is. Help?
P.S. I've seen this code example:
p { font-size: 10px; }
p { line-height: 120%; } /* 120% of 'font-size' */
What is that supposed to mean? Why on earth would anyone want to set a line height to a percentage value of a font size?
回答1:
OK, so I've decided to sum up the answers.
- line-height's percentage value is relative to the current font-size.
- em units is always relative to font-size.
- Percents depends on context. For example, if they're used in font-size, they will be relative to the current font-size; if it's in height, they will be relative to the height.
- It changes a little bit when parent tag has font size declared as "small", "medium" or "large", because values of these are affected by browser's setting. In this context 1em =\= 100%, 1em seems to make setting a bit more "small" or a bit more "large" than 100%, read about it here.
Thank you, guys. :)
回答2:
Line height is usually a multiple of the font size. In fact, it is the only value for which you don't have to specify a unit:
p { line-height: 1.2; } /* = 1.2em = 1.2*font-size = 120% of font-size */
If line-height is proportionate to font-size, it is easier to resize the font, without having to worry about fixed line-height.
回答3:
1em = 100%, 2em = 200%, 1,4 em = 140% and so on. However, it's actually contex dependent. I think ems are more "mobile friendly", but that's up to developer.
In css you use percentage values because users can have a different screen resolutions. When you don't want blank spaces in your js generated content for example.
1em means "equeal to the actual font-size", 2 - "2 times the font-size", means ems adapt to users settings.
So it changes a little bit when parent tag has font size declared as "small", "medium" or "large", because values of these are affected by browser's setting. In this context 1em =\= 100%, 1em seems to make setting a bit more "small" or a bit more "large" than 100%, read about it here:
http://kyleschaeffer.com/user-experience/css-font-size-em-vs-px-vs-pt-vs/
There could be performance differences, but that would depend on a browser.
来源:https://stackoverflow.com/questions/15311338/whats-the-difference-between-em-units-and-percents