在CSS中,咱們能夠經過下面的樣式實現DIV元素中文本超長後自動截斷並以省略號結尾:
overflow: hidden;
word-break: normal;
text-overflow: ellipsis;
text-overflow: ellipsis是實現文本截斷後以省略號結尾的關鍵樣式,但問題是若是添加該樣式則DIV元素內的文本沒法自動換行,也就是說該效果只被容許在單行文本上實現。另外,word-break: normal能夠防止文字被部分截斷,這個在內容爲英文的狀況下顯得尤爲重要。
要實現多行文本自動截斷以省略號結尾的效果,一般的作法是使用JavaScript腳本。下面這些文章給出瞭如何經過腳本進行字符串截斷,不過僅限於英文環境。
使用純CSS樣式來實現該效果則會稍微有些麻煩,你須要懂得如何在CSS中進行hack。這裏是一個能夠在多個通用瀏覽器中實現該效果的例子:
複製代碼
<!DOCTYPE HTML>
<html>
<head>
<style>
html, body, p { margin: 0; padding: 0; font-family: sans-serif;}
.ellipsis {
overflow: hidden;
height: 200px;
line-height: 25px;
margin: 20px;
border: 5px solid #AAA; }
.ellipsis:before {
content:"";
float: left;
width: 5px; height: 200px; }
.ellipsis > *:first-child {
float: right;
width: 100%;
margin-left: -5px; }
.ellipsis:after {
content: "\02026";
box-sizing: content-box;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
float: right; position: relative;
top: -25px; left: 100%;
width: 3em; margin-left: -3em;
padding-right: 5px;
text-align: right;
background: -webkit-gradient(linear, left top, right top,
from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }
</style>
</head>
<body>
<div class="ellipsis"><div>
<p>Call me Ishmael. Some years ago – never mind how long precisely – having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen, and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off – then, I account it high time to get to sea as soon as I can.</p>
</div></div>
</body>
</html>
複製代碼
經過修改.ellipsis和.ellipsis:before樣式中height屬性的值來指定容器的高度。該樣式的實如今多個不一樣版本的瀏覽器下測試經過,注意若是你是在IE下查看則須要確保你的文檔模型必須是在標準模式下,即Document Mode必須是Standards。