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

CSS文本省略号仅显示内容首行而非所有段落首行的实现方法

如何实现仅保留文本第一行并添加省略号的效果?

我尝试为文本应用省略号效果,但当前设置会截取所有段落的首行。我仅希望保留内容的第一行并添加省略号。

示例内容

While sending message via websocket this code is triggered. However, '+ msg +' does not detect new lines (line breaks) in the message. Every sentence appears in the same line.

Optimize this jquery code so that '+ msg +' can detect new lines.

现有CSS代码

.content .message {
  font-size: 0.8rem;
  color: #afb9d7;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

HTML结构

<div class="content">
  <div class="name">Shreyansh Jha </div>
  <div class="message " data-msg="While sending message via websocket this code is triggered. However, '+ msg +' does not detect new lines (line breaks) in the message. Every sentence appears in the same line. <br />
    <br />
    Optimize this jquery code so that '+ msg +' can detect new lines.">While sending message via websocket this code is triggered. However, '+ msg +' does not detect new lines (line breaks) in the message. Every sentence appears in the same line. <br>
    <br>
    Optimize this jquery code so that '+ msg +' can detect new lines.
  </div>
</div>

解决方案

当前CSS里的white-space: nowrap会强制所有文本在一行显示,忽略<br>等换行符,导致整个内容被压缩成一行后截断,不符合需求。只需调整CSS属性,实现仅显示第一行并添加省略号:

.content .message {
  font-size: 0.8rem;
  color: #afb9d7;
  text-overflow: ellipsis;
  overflow: hidden;
  /* 核心修改:限制仅显示一行 */
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
  • display: -webkit-box:将元素设置为WebKit内核专属的弹性盒模型
  • -webkit-line-clamp: 1:明确限制内容只显示1行
  • -webkit-box-orient: vertical:指定内容采用垂直排版方向

修改后,元素会正常识别<br>为换行,仅保留第一行内容,超出部分自动添加省略号,后续段落会被隐藏,完全匹配期望效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 14:47:28