line-height的语法定义:line-height: normal | <number> | <length> | <percentage>
normal 根据浏览器决定,一般为1.2。
number 仅指定数字时(无单位),实际行距为字号乘以数字得出的结果。可以理解为一个系数,子元素仅继承该系数,子元素的真正行距是分别与自身元素字号相乘的计算结果。大多数情况下推荐使用,可以避免一些意外的继承问题。
length 具体的长度,如px/em等。
percentage 百分比,100%与1em相同。
line-height这几个属性之间的区别主要就在于继承的问题。
1. percentage 百分比
body{ font-size:14px; line-height:150%; }
h1{ font-size:32px; }
p{ font-size:12px; }
如上,line-height的百分比和body的文字大小计算出值,这个值将会继承下去。所有继承下来的元素会忽略本身的font-size,而使用相同的计算出来的line-height。
element | font-size | line-height | 计算后的line-height |
body | 14px | 14px * 150% = 21px | 21px |
h1 | 32px | 继承计算后的值 | 21px |
p | 12px | 继承计算后的值 | 21px |
2. length 具体的长度
body{ font-size:14px; line-height:20px; }
h1{ font-size:32px; }
p{ font-size:12px; }
这个长度值20px同样会被后代元素所继承。
element | font-size | line-height | 计算后的line-height |
body | 14px | 20px | 20px |
h1 | 32px | 继承值 | 20px |
p | 12px | 继承值 | 20px |
3. number 纯数字
body{ font-size:14px;line-height:1.5; }
h1{ font-size:32px; }
p{ font-size:12px; }
现在所有继承下来的元素都会根据字体大小来确定line-height的值。
element | font-size | line-height | 计算后的line-height |
body | 14px | 1.5 | 1.5 * 14px = 21px |
h1 | 32px | 系数:1.5 | 1.5 * 32px = 48px |
p | 12px | 系数:1.5 | 1.5 * 12px = 18px |
可以看出,line-height会随着相关的font-size做相应的比例缩放。
4. 值normal
line-height被设置为normal(约为1.2)。所有继承下来的元素也不会忽略自身的font-size,跟number数字一样,line-height也会随着相关的font-size做相应的比例缩放,系数约为1.2 。
那么,哪一种是最好的方案呢?
一般来说,设置行高值为number是最理想的方式,因为它会随着对应的font-size而缩放。在多数情况下,很难确定一个完美的line-height,所以这就根据需求在不同情况下选择不同的方案。