em详解

最近详细阅读了一下CSS2.2文档,对em单位有了深刻的认识

原文在此:
The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element. It may be used for vertical or horizontal measurement. (This unit is also sometimes called the quad-width in typographic texts.)

大致意思是:

'em'单位等于应用该规则的元素的'font-size'属性的计算值。一种异常情况是当'em'出现在'font-size'属性本身的值中时,这种情况下参考父元素的字体大小。它可以用在竖直或者水平测量中(这个单位在排版文本中有时也叫quad-width,四边宽度?)

例1:当em应用在非字体上时

1 <div class="con" style="font-size: 30px;width: 200px; height: 200px; background: grey;">
2         <div class="con-1" style="font-size: 20px; width: 5em; height: 5em; background: red;">cococe</div>
3         cococe
4 </div>
cococe
cococe

解析:此时.con-1元素的宽为100px,高为100px,因为此时em的大小为当前作用元素font-size大小,也即是20px。

 

例2:当em应用在字体上时

1 <div class="con" style="font-size: 30px; width: 200px; height: 200px; background: grey;">
2         <div class="con-1" style="font-size: 1em; width: 5em; height: 5em; background: lightgrey;">cococe</div>
3         cococe
4 </div>
cococe
cococe

 解析:此时字体大小为30px,即为父元素字体大小,相应的高为150px,宽为150px。

注意:子元素不会继承父元素指定的相对值,而是继承计算值

例如:

1 <div class="con" style="font-size:20px;width:200px;height:200px;background:grey; text-indent: 1em;">
2         cococe
3         <div class="con-1" style="font-size:18px;width:5em;height:5em;background:lightgrey;">cococe</div>
4 </div>
cococe
cococe

 解析:子元素.con-1的text-indent继承的是父元素的1em的计算值,即为20px,而不是继承父元素的相对值1em,假如继承的是1em的话,那么子元素的text-indent机会被解析为18px,那么图中的父元素与子元素的text-indent就不会相同。

posted @ 2016-08-21 23:37  cococe  阅读(803)  评论(0编辑  收藏  举报