文本溢出省略样式

实现单行和多行文本溢出时显示省略号的 CSS 方案

问题

如何实现单行和多行文本溢出时显示省略号?

解答

单行文本溢出

单行文本溢出需要三个 CSS 属性配合使用:

p {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 400px;
    line-height: 40px;
    height: 40px;
    border: 1px solid red;
}

属性说明:

  • overflow: hidden - 隐藏溢出内容
  • white-space: nowrap - 强制文本在一行内显示
  • text-overflow: ellipsis - 溢出部分显示省略号

多行文本溢出

方案一:基于 Webkit 的行数截断(推荐移动端使用)

p {
    width: 400px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}

这种方案简洁高效,但仅支持 Webkit 内核浏览器。如果文本包含长英文或数字,需添加 word-wrap: break-word

方案二:伪元素 + 定位(兼容性好)

.demo {
    position: relative;
    line-height: 20px;
    height: 40px;
    overflow: hidden;
}

.demo::after {
    content: "...";
    position: absolute;
    bottom: 0;
    right: 0;
    padding-left: 40px;
    background: linear-gradient(to right, transparent, #fff 55%);
}

通过伪元素绝对定位到文本末尾,配合渐变背景遮盖溢出文字。这种方案兼容性好,支持响应式截断。

方案三:JavaScript + CSS

CSS 部分:

p {
    position: relative;
    width: 400px;
    line-height: 20px;
    overflow: hidden;
}

.p-after:after {
    content: "...";
    position: absolute;
    bottom: 0;
    right: 0;
    padding-left: 40px;
    background: linear-gradient(to right, transparent, #fff 55%);
}

JavaScript 部分:

$('p').each(function() {
    var lineHeight = parseInt($(this).css("line-height"));
    var height = parseInt($(this).height());
    
    if ((height / lineHeight) > 3) {
        $(this).addClass("p-after");
        $(this).css("height", "60px");
    } else {
        $(this).removeClass("p-after");
    }
});

动态计算文本行数,超过指定行数时添加省略号样式。

关键点

  • 单行溢出必须同时设置 overflow: hiddenwhite-space: nowraptext-overflow: ellipsis
  • -webkit-line-clamp 方案最简洁,但仅支持 Webkit 内核,适合移动端
  • 伪元素方案兼容性最好,通过绝对定位和渐变背景实现省略效果
  • 英文或数字文本需添加 word-break: break-allword-wrap: break-word 实现单词拆分
  • JavaScript 方案可以动态控制,但需要额外的性能开销