有时,我们需要对某段文字进行截断处理,多余的字符显示…

1
<div class="words">For a long time it seemed to me that life was about to begin , real life. But, there was always some obsacle in the way, something to be gotten through first, some unfinnished business, time still to be served or a debt to be paid. Then life would begin.</div>

单行

代码

1
2
3
4
5
6
.words {
width: 400px;
overflow: hidden; /*超过部分不显示*/
text-overflow: ellipsis; /*超过部分用点点表示*/
white-space: nowrap; /*不换行*/
}

效果

For a long time it seemed to me that life was about to begin , real life. But, there was always some obsacle in the way, something to be gotten through first, some unfinnished business, time still to be served or a debt to be paid. Then life would begin.

多行

-webkit 代码

1
2
3
4
5
6
7
8
9
// webkit
.words {
width: 400px;
overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /*规定超过两行的部分截断*/
-webkit-box-orient: vertical;
}

-webkit 效果

For a long time it seemed to me that life was about to begin , real life. But, there was always some obsacle in the way, something to be gotten through first, some unfinnished business, time still to be served or a debt to be paid. Then life would begin.

兼容代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 兼容其它内核 padding需要根据实际情况计算
.words {
width: 400px;
position: relative;
line-height: 1.4em;
/* 高度=2倍的行高 */
height: 2.8em;
overflow: hidden;
}
.words::after {
content: "...";
position: absolute;
bottom: 0;
right: 0;
padding: 0 35px 1px 0;
}

兼容代码效果

For a long time it seemed to me that life was about to begin , real life. But, there was always some obsacle in the way, something to be gotten through first, some unfinnished business, time still to be served or a debt to be paid. Then life would begin.

插件

也有一些通过js实现的截断插件,例如 jQuery.dotdotdotClamp.js