12 line-height 如何继承
html
<!-- 如下代码,p 标签的行高将会是多少?-->
<style>
body {
font-size: 20px;
line-height: 200%;
}
p {
font-size: 16px;
}
</style>
<body>
<p>AAA</p>
</body>
<!-- 答案是 40px -->- 写具体数值,如 30px,则继承该值;
- 写比例,如 2/1.5,则继承该比例;
- 写百分比,如 200%,则继承该百分比,但是是相对于父元素的 font-size 计算的。
查看代码
html
<div class="fixed-line-height">
<p>
.fixed-line-height { font-size: 16px; line-height: 30px; } <br />
p { font-size: 14px; line-height: <span></span> }
</p>
</div>
<div class="ratio-line-height">
<p>
.ratio-line-height { font-size: 18px; line-height: 1.5; } <br />
p { font-size: 14px; line-height: <span></span> }
</p>
</div>
<div class="percentage-line-height">
<p>
.percentage-line-height { font-size: 20px; line-height: 200%; } <br />
p { font-size: 14px; line-height: <span></span> }
</p>
</div>css
body {
font-size: 16px;
}
.fixed-line-height,
.ratio-line-height,
.percentage-line-height {
width: 500px;
margin: 10px;
padding: 5px;
background-color: #ccc;
border-radius: 5px;
}
.fixed-line-height {
font-size: 16px;
line-height: 30px; /* 继承具体数值 */
}
.ratio-line-height {
font-size: 18px;
line-height: 1.5; /* 继承比例 */
}
.percentage-line-height {
font-size: 20px;
line-height: 200%; /* 继承百分比 */
}
.fixed-line-height p,
.ratio-line-height p,
.percentage-line-height p {
font-size: 14px;
}js
function displayLineHeight(element) {
const elementStyle = getComputedStyle(element)
const elementLineHeight = elementStyle.lineHeight // 元素的 line-height
const span = element.querySelector('span')
span.innerText = elementLineHeight
}
const divs = document.querySelectorAll('div')
divs.forEach((div) => {
const p = div.querySelector('p')
displayLineHeight(p)
}).fixed-line-height p元素的line-height为 30px。因为继承的是具体的数值,所以不会发生任何变化。.ratio-line-height p元素的line-height为 21px。因为继承的是比例,所以计算公式为 1.5 * 14px = 21px。.percentage-line-height p元素的line-height为 40px。因为继承的是百分比,所以计算公式为 200% * 20px = 40px。