css3 文本溢出显示省略号

文字排版常见需求:单行文本溢出显示省略号,多行文本溢出显示省略号。

其中多行文本溢出显示省略号,浏览器兼容不是太好,手机上使用没什么问题,PC 上兼容不太行,参考文章后面兼容性。

示例

example.html

效果:

源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>text-overflow</title>
</head>

<body>
<style type="text/css">
.test_demo_clip {
overflow: hidden;
white-space: nowrap;
width: 200px;
background: #ccc;
}

.test_demo_ellipsis {
/* 核心代码 */
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
/* 核心代码 */
width: 200px;
background: #ccc;
}

.test_demo_more {
/* 核心代码 */
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
/* 核心代码 */
width: 200px;
background: #ccc;
}
</style>
<h2>默认效果</h2>
<div class="test_demo_clip">
不显示省略标记,而是简单的裁切条
</div>
<h2>单行效果</h2>
<div class="test_demo_ellipsis">
当对象内文本溢出时显示省略标记
</div>
<h2>多行效果</h2>
<div class="test_demo_more">
多行效果文本溢出时显示省略标记,
多行效果文本溢出时显示省略标记,
多行效果文本溢出时显示省略标记,
</div>
</body>

</html>

使用 sass mixins

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
文字溢出显示省略号
使用:单行使用 @include ell();
使用:多行使用 @include ell(3);
*/
@mixin ell($line: 1) {
@if $line==1 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
@else {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: $line;
-webkit-box-orient: vertical;
}
}

兼容性

Can I use

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-03-16/css3-text-overflow/

如果您觉得文章不错,可以点击文章中的广告支持一下!