[css] line-height 百分比单位和数值单位的区别

前言

CSS 中的 line-height 属性值有 normal | <number> | <length> | <percentage> | inherit。

属性值:
normal w3c规范建议厂商根据字体设置一个"reasonable"的<number>类型的值,建议在 1.0 到 1.2 之间。
<number> | <length> | <percentage> 下面单独解释,先看一段代码:

code

<style>
div   { font-size: 20px; line-height: 30px;}
div.a { font-size: 20px; line-height: 150%;}
div.b { font-size: 20px; line-height: 1.5;}
div > p.a { font-size: 30px;}
div > p.b { font-size: 40px;}
</style>  
</head>
<body>
<div>
  <p class="a">Lorem ipsum dolor </p>
  <p class="b">Lorem ipsum dolor </p>
</div>   
<div class="a">
  <p class="a">Lorem ipsum dolor </p>
  <p class="b">Lorem ipsum dolor </p>
</div> 
<div class="b">
  <p class="a">Lorem ipsum dolor </p>
  <p class="b">Lorem ipsum dolor </p>
</div>  

value process

font-sizeinitialdeclarationcascadedspecifiedcomputedactual
div20pxnormal30px30px30px30px30px
div>p.a30pxnormal 30px30px30px
div>p.b40pxnormal 30px30px30px
div.a20pxnormal150%150%150%30px30px
div.a>p.a30pxnormal 30px30px30px
div.a>p.b40pxnormal 30px30px30px
div.b20pxnormal1.51.51.51.530px
div.b>p.a30pxnormal 1.51.545px
div.b>p.b40pxnormal 1.51.560px

解释

div, div.a , div.b 元素的 line-height 的最终值(actual value)都是一样的,都是 30px, 不一样的是 computed value .
为什么 Computed value 不一样呢? 根据 line-height 的 computed value 定义

Computed value: for <length> and <percentage> the absolute value; otherwise as specified)

对于属性值类型为 "<length>, <percentage>" 的 div ,div.a 元素, computed value 是一个绝对值,所以属性值为 30px 和 150% 都会转化为绝对值,也就是 30px; 而对于属性值为 <number> 类型的 div.b 元素的 computed value 就是 1.5。

computed value 不同会造成什么样的影响呢? 答案是对继承有影响。根据规范的的定义:(https://www.w3.org/TR/2011/REC-CSS2-20110607/cascade.html#specified-value)

If the cascade results in a value, use it.
Otherwise, if the property is inherited and the element is not the root of the document tree, use the computed value of the parent element.
Otherwise use the property's initial value. The initial value of each property is indicated in the property's definition.

对于没有定义且可以继承的属性,它会继承父元素该属性的 computed value;在这个例子中,由于 line-height 是可继承的, 所以对于div, div.a的子元素 p 继承的 line-height 值都是 30px, 而对于div.b的子元素 p 继承的 line-height 值是 1.5 ,从而导致了 p 元素 actual value 的不同。

参考

  1. https://www.w3.org/TR/CSS2/visudet.html#propdef-line-height

  2. https://www.w3.org/TR/css3-cascade/#value-stages

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值