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就不会相同。

转载于:https://www.cnblogs.com/cococe/p/10475784.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值