CSS實現單行、多行文本溢出顯示省略符號的實現方法

來源:互聯網
上載者:User
如果實現單行文本的溢出顯示省略符號同學們應該都知道用text-overflow:ellipsis屬性來,當然還需要加寬度width屬來相容部分瀏覽

一、單行溢出

1,單行溢出,超出部分顯示...或者截取。前提必須有寬度。
CSS:{width:xxpx;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;},截取為clip;

實現代碼:

width:300px;    overflow: hidden;    text-overflow:ellipsis;    whitewhite-space: nowrap;

效果


但是這個屬性只支援單行文本的溢出顯示省略符號,如果我們要實現多行文本溢出顯示省略符號呢。

接下來重點說一說多行文本溢出顯示省略符號,如下。

二、多行溢出

{display:-webkit-box;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp:2;-webkit-box-orient:vertical;}

實現方法:

display: -webkit-box;    -webkit-box-orient: vertical;    -webkit-line-clamp: 3;    overflow: hidden;

效果


適用範圍:

因使用了WebKit的CSS擴充屬性,該方法適用於WebKit瀏覽器及移動端;

註:

1.-webkit-line-clamp用來限制在一個塊元素顯示的文本的行數。 為了實現該效果,它需要組合其他的WebKit屬性。常見結合屬性:
2.display: -webkit-box; 必須結合的屬性 ,將對象作為Auto Scaling盒子模型顯示 。
3.-webkit-box-orient 必須結合的屬性 ,設定或檢索伸縮盒對象的子項目的相片順序 。

實現方法:

p{position: relative; line-height: 20px; max-height: 40px;overflow: hidden;}    p::after{content: "..."; position: absolute; bottombottom: 0; rightright: 0; padding-left: 40px;    background: -webkit-linear-gradient(left, transparent, #fff 55%);    background: -o-linear-gradient(rightright, transparent, #fff 55%);    background: -moz-linear-gradient(rightright, transparent, #fff 55%);    background: linear-gradient(to rightright, transparent, #fff 55%);    }

適用範圍:
該方法適用範圍廣,但文字未超出行的情況下也會出現省略符號,可結合js最佳化該方法。

註:

1.將height設定為line-height的整數倍,防止超出的文字露出。
2.給p::after添加漸層背景可避免文字只顯示一半。
3.由於ie6-7不顯示content內容,所以要添加標籤相容ie6-7(如:<span>…<span/>);相容ie8需要將::after替換成:after。

指令碼之家小編補充:

ie核心的瀏覽器一定要定義line-height與高度,-webkit-line-clamp意思就是幾行,例如

line-height: 20px;

max-height: 40px;

display: -webkit-box;

-webkit-box-orient: vertical;

-webkit-line-clamp: 2;

overflow: hidden;

-webkit-line-clamp

-webkit-line-clamp 是一個 不規範的屬性(unsupported WebKit property),它沒有出現在 CSS 規範草案中。
限制在一個塊元素顯示的文本的行數。 為了實現該效果,它需要組合其他外來的WebKit屬性。常見結合屬性:
display: -webkit-box; 必須結合的屬性 ,將對象作為Auto Scaling盒子模型顯示 。
-webkit-box-orient 必須結合的屬性 ,設定或檢索伸縮盒對象的子項目的相片順序 。
text-overflow,可以用來多行文本的情況下,用省略符號“...”隱藏超出範圍的文本 。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.