CSS實現單行、多行文字溢位時顯示省略號
阿新 • • 發佈:2019-02-12
text-overflow屬性
這個屬性針對那些在塊級元素溢位的內容有效。
文字可能在以下情況下溢位:
- 由於某種原因無法換行,如設定了white-space:no-wrap
- 或者一個單詞因為太長而不能被合理地安置
為了能讓text-overflow屬性生效,必須在元素上新增幾個額外的屬性:
- overflow:hidden
- white-space:no-wrap:不換行,只顯示單行文字
text-overflow的幾個取值:
- clip(預設值):超出的部分直接截斷
ellipsis:超出的部分用省略號顯示。這個省略號被新增在內容區域中,因此會減少顯示的文字。如果空間太小到連省略號都容納不下,那麼這個省略號也會被截斷。
自定義字串(實驗屬性,大部分瀏覽器不支援):超出的部分用自定義字串顯示。字串內容將被新增在內容區域中,所以會減少顯示出的文字。如果空間太小到連字串都容納不下,那麼這個字串也會被截斷。
<p class="overflow-visible">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p class="overflow-clip">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
<p class="overflow-ellipsis">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
p {
width: 200px;
border: 1px solid;
padding: 2px 5px;
/* BOTH of the following are required for text-overflow */
white-space: nowrap;
overflow: hidden;
}
.overflow-visible {
white-space: initial ;
}
.overflow-clip {
text-overflow: clip;
}
.overflow-ellipsis {
text-overflow: ellipsis;
}
多行文字的溢位問題
text-overflow只能應用於單行文字的溢位處理。
有一個-webkit-line-clamp的實驗屬性貌似可以,但是搜不到什麼資料。
可以使用偽元素來解決:
- 將height設為line-height的整數倍(要顯示幾行就設為幾倍)
- 使用::after偽元素,絕對定位在元素的右下角。
- 可以給偽元素新增漸變背景避免遮蓋文字。
- 要相容ie6-7的話可以使用
<span>...</span>
來完成
p{
line-height:20px;
height:60px;
overflow:hidden;
position:relative;
width:100px;
}
p::after{
content:"...";
position:absolute;
bottom:0;
right:0;
background:-webkit-linear-gradient(left,transparent,#fff 55%);
background:-o-linear-gradient(right,transparent,#fff 55%);
background:-moz-linear-gradient(right,transparent,#fff 55%);
background:linear-gradient(to right,transparent,#fff 55%);
}