多行文本溢出显示省略号(…) text-overflow: ellipsis

关于text-overflow

text-overflow 属性规定当文本溢出包含元素时发生的事情。

默认值: clip
继承性: no
版本: CSS3
JavaScript 语法: object.style.textOverflow="ellipsis"

语法: text-overflow: clip|ellipsis|string;

描述  
clip 修剪文本。  
ellipsis 显示省略符号来代表被修剪的文本。  
string 使用给定的字符串来代表被修剪的文本。

这里主要说说 text-overflow: ellipsis;

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <style> 
 5 div.test
 6 {
 7 white-space:nowrap; 
 8 width:12em; 
 9 overflow:hidden; 
10 border:1px solid #000000;
11 }
12 </style>
13 </head>
14 <body>
15 
16 
17 <div class="test" style="text-overflow:ellipsis;">This is some long text that will not fit in the box</div>
18 
19 
20 </body>
21 </html>

效果如下:

多行文本溢出显示省略号(…) text-overflow: ellipsis

常见的想要的效果实现了~~细心你会发现text-overflow:ellipsis; 不可独立使用必须结合overflow:hidden;  white-space:nowrap;才生效。

然而white-space:nowrap; 是指不换行,就是说只能一行显示。

但是有时我们想要实现多行的情况下,在最后一行的最后用“…”来表示。

多行显示text-overflow: ellipsis

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8   <p>多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示多行显示</p>
 9     
10 </body>
11 </html>

css如下

 1 p{
 2   width:200px;
 3   height: 32px;
 4   overflow: hidden;
 5   text-overflow: ellipsis;
 6   display: -webkit-box;
 7   -webkit-line-clamp: 2;
 8   -webkit-box-orient: vertical;
 9   font-size: 14px
10 }

demo效果:http://jsbin.com/depogojufi/edit?html,css,output

这里用了一个不是很常见的属性 -webkit-line-clamp

在WebKit浏览器或移动端(绝大部分是WebKit内核的浏览器)的页面实现比较简单,可以直接使用WebKit的CSS扩展属性(WebKit是私有属性)-webkit-line-clamp ;注意:这是一个 不规范的属性(unsupported WebKit property),它没有出现在 CSS 规范草案中。

-webkit-line-clamp用来限制在一个块元素显示的文本的行数。 为了实现该效果,它需要组合其他的WebKit属性。
常见结合属性:

1,display: -webkit-box; 必须结合的属性 ,将对象作为弹性伸缩盒子模型显示 。

2,-webkit-box-orient 必须结合的属性 ,设置或检索伸缩盒对象的子元素的排列方式 。

3,text-overflow: ellipsis;,可以用来多行文本的情况下,用省略号“…”隐藏超出范围的文本 。