You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为h3的line-height加rem单位导致边距重叠的原因

问题

给h3元素的line-height添加rem单位后,出现两个异常:

  • 上方p元素的margin和h3元素直接接触
  • h3自身的margin与其文字内容重叠
    移除单位后恢复正常,想了解背后的原因。

相关代码

CSS代码

.step-number {
  font-size: 8.6rem;
  font-weight: 600;
  color: #ddd;
  margin-bottom: 1.2rem;
}

.step-description {
  font-size: 1.8rem;
  line-height: 1.8;
}

.heading-tertiary {
  font-size: 3rem;
  line-height: 1.2rem;
  margin-bottom: 3.2rem;
}

HTML代码

<p class="step-number">01</p>
<h3 class="heading-tertiary">Tell us what you like (and what not)</h3>
<p class="step-description">
Never again waste time thinking about what to eat! Omnifood AI will create a 100% personalized weekly meal plan just for you. It makes sure you get all the nutrients and vitamins you need, no matter what diet you follow!
</p>
原因分析

核心差异在于line-height带单位和不带单位的计算逻辑完全不同:

  1. 无单位的line-height是动态倍数
    当设置line-height: 1.2时,这个值是基于元素自身font-size的倍数。你的h3字体大小是3rem,实际行高就是3rem × 1.2 = 3.6rem,这个高度足够容纳文字内容,元素的盒模型高度也会匹配行高,不会出现内容和margin重叠的情况,上方p的margin也能和h3的正常间距共存。

  2. 带单位的line-height是固定值
    你给h3设置了line-height: 1.2rem,但h3的font-size是3rem——这就导致行高比字体本身的高度还小。文字的实际高度由字体大小决定,当行高小于字体高度时,文字会溢出到行高限定的元素高度之外:

    • h3元素的盒模型高度被固定为1.2rem,远小于文字需要的高度,所以h3的margin会和溢出的文字重叠;
    • 上方p的margin-bottom:1.2rem和h3的实际高度一致,视觉上就呈现出p的margin直接碰到h3内容的效果。

简单来说,带单位的line-height如果设成比字体大小小的固定值,会让元素盒模型高度不足以容纳文字,进而引发内容与margin重叠、相邻元素间距异常的问题。而无单位的倍数line-height会自动适配字体大小,保证足够的行高容纳内容。

内容的提问来源于stack exchange,提问作者Nandakumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:25:10