CSS line-height三种赋值方式的区别
1.直接在某个元素上使用,下面三种没有区别:
p {
line-height: 1.5em;
font-size: 20px;
}
p {
line-height: 1.5;
font-size: 20px;
}
p {
line-height: 150%;
font-size: 20px;
}
三种方式得到的行高都是1.5×20px=30px;
2.三者的区别是在给父元素使用行高,子元素继承的方式有区别
第一种父元素line-height带单位px;子元素直接继承;
第二种父元素line-height带单位em;使元素以其父元素font-size值参考来计算自己的行高。
div {
font-size: 20px;
line-height: 2em;
background-color: #999;
}
p {
font-size: 30px;
background-color: red;
}
<div>
<p>123</p>
</div>
子元素行高40px;
第三种:纯数字,把比例传递给后代。
div {
font-size: 20px;
line-height: 2;
background-color: #999;
}
p {
font-size: 30px;
background-color: red;
}
子元素行高60px;
第四种:百分比,将计算后的值传给后代。
div {
font-size: 40px;
line-height: 200%;
background-color: #999;
}
p {
font-size: 30px;
background-color: red;
}
</style>
<div>
<p>123</p>
</div>
子盒子行高80px;
总结:
父盒子line-height的单位为px时,子盒子直接继承父盒子的行高。
父盒子line-height的单位为em时,子盒子以其父元素font-size值参考来计算自己的行高。
父盒子line-height的值为纯数字时,父盒子把比例传递给后代。
父盒子line-height的单位为%时,父盒子先计算然后把值传递给后代。
em与%有相同的作用。
一句话概括:子元素继承line-height的时候,带单位的先计算再继承,不带单位的直接继承。(如果父元素没设置字体大小,则直接根据子元素字体的大小+2px来设置行高)