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

如何在line-height值较大时仅选中文本行而非行间距?

如何让大line-height的p标签仅选中文本内容而非行间距

当给<p>标签设置较大的line-height(比如line-height: 6)时,文本选中区域会覆盖整行,包含大量多余的行间距。如果需要在单个<p>标签内实现类似多个设置小line-height(如1.45)的<p>标签的选中效果——仅选中文本本身、不包含额外行间距,可以用以下方法:

核心思路

不要直接给<p>设置大line-height,而是用内联块元素(如<span>)包裹每段文本内容,给内联块设置合适的line-height,再通过margin控制行与行之间的间距。这样文本选中时只会覆盖内联块的文本区域,不会包含多余间距。

实现代码

CSS

p {
  font-size: 18px;
}
p span {
  display: inline-block;
  line-height: 1.45; /* 目标的小line-height值 */
  margin: 1.275em 0; /* 计算方式:(6 - 1.45)/2 * 1em,补全与原大line-height等价的上下间距 */
}

HTML

<p>
  <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Id, ratione saepe?</span>
  <span>Rerum, autem! Nulla consequatur, optio praesentium aliquid modi, beatae fugiat asperiores suscipit enim excepturi hic, magnam fugit? Voluptates, fuga?</span>
</p>

效果说明

视觉上,这个方案和原大line-height的<p>标签表现一致,但文本选中时只会选中<span>包裹的文本区域,和多个设置line-height:1.45的<p>标签的选中效果完全相同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:23:10