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

如何避免连字符单词在文本溢出时被拆分显示?

解决-webkit-line-clamp截断时连字符单词被拆分的问题

针对带连字符的单词(比如breath-taking)在两行截断时被拆分显示的问题,给你两个可行的解决方案:

方案一:用CSS属性强制单词不拆分

修改p标签样式,添加overflow-wrap: normal属性,它会让浏览器只在空格处换行,不会把带连字符的单词拆分开:

.container {
  border: 1px solid green;
  width: 350px;
}

p {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow-wrap: normal; /* 禁止单词内换行,连字符单词会被视为整体 */
}

调整后,容器宽度足够时单词完整显示;宽度不足时,整个单词会被推到下一行,若两行仍放不下,就会被整体截断成省略号,不会出现breath-...这类拆分情况。

方案二:用span包裹单个单词强制不换行

如果方案一有浏览器兼容问题,可直接把带连字符的单词用span包裹,设置white-space: nowrap强制单词不拆分:

修改后的HTML:

<div class="container">
  <p>
    Take to the skies to experience the <span style="white-space: nowrap">breath-taking</span> views.
    Take to the skies to experience the <span style="white-space: nowrap">breath-taking</span> views. Take to the skies to experience the <span style="white-space: nowrap">breath-taking</span> views.
  </p>
</div>

这个方法针对特定单词生效,不管容器宽度如何,被包裹的单词都不会被拆分,要么完整显示,要么被整体截断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:21:11