看到簡介標註為只能顯示3行文本,多於3行顯示3行,本準備採取字串截取矇混過關(不能原諒的事情是對自己沒有要求,簡直沒有下限),後查看了網上的解決方案,特此分享。
思路
現在假設想要顯示的文本行數是N行,首先設定文本容器的max-height = N 乘以 line-height,第N行顯示的文本為部分文本 + ... + 展開全部。設定文本容器的字型顏色為背景色,虛擬元素before和after的content都為常值內容。藉助虛擬元素before顯示(N - 1)行元素,z-index = 1(在文本容器、before虛擬元素、after虛擬元素、[展開全部]按鈕中確保before虛擬元素z-index最大)。after虛擬元素的padding-right寬度為[展開全部]按鈕的寬度(單位為em),text-indent = (N - 1) * [展開全部]按鈕的寬度(如何理解縮排? 通過設定after虛擬元素的padding-right為第N行的[展開全部]按鈕留位置,由於第1行、第2行...第(N - 1)行都少顯示[展開全部]按鈕寬度的字型,所以,為了確保虛擬元素after在第N行中顯示正確,需要負值縮排(N - 1) 乘以 [展開全部]按鈕的寬度)
完整代碼
<div class="desc" title="Jennifer Joanna Aniston (born February 11, 1969)[1] is an American actress, producer, and businesswoman.[2] The daughter of Greek actor John Aniston and American actress Nancy Dow, Aniston gained worldwide recognition for portraying Rachel Green on the popular television sitcom Friends (1994–2004), a role which earned her a Primetime Emmy Award, a Golden Globe Award, and a Screen Actors Guild Award. The character was widely popular during the airing of the series and was later recognized as one of the 100 greatest female characters in United States television"> Jennifer Joanna Aniston (born February 11, 1969)[1] is an American actress, producer, and businesswoman.[2] The daughter of Greek actor John Aniston and American actress Nancy Dow, Aniston gained worldwide recognition for portraying Rachel Green on the popular television sitcom Friends (1994–2004), a role which earned her a Primetime Emmy Award, a Golden Globe Award, and a Screen Actors Guild Award. The character was widely popular during the airing of the series and was later recognized as one of the 100 greatest female characters in United States television <button>更多</button></div>
.desc { position: relative; width: 400px; /*用像素表示,不要用em,以免造成不同瀏覽器下計算出現小數點取捨不同導致1像素的差距【行高*截取行數】*/ overflow: hidden; max-height: 72px; font-size: 16px; line-height: 24px; overflow: hidden; word-wrap: break-word; /*強制打散字元*/ word-break: break-all; background: #fff; /*同背景色*/ color: #fff; &:after, &:before { content: attr(title); position: absolute; left: 0; top: 0; width: 100%; /*實際文本顏色*/ color: #000; } &:before { display: block; overflow: hidden; /*顯示在最上面,展示前面的(截取行數-1)行字元*/ z-index: 1; /*根據行高和截取行數調整,值為[(截取行數-1)*行高]*/ max-height: 48px; /*同背景色*/ background: #fff; } &:after { display: -webkit-box; -webkit-box-orient: vertical; -webkit-box-sizing: border-box; box-sizing: border-box; /*截取行數*/ -webkit-line-clamp: 3; /*行首縮排字元數,值為[(截取行數-1)*尾部留Null 字元數]*/ text-indent: -8em; /*尾部留Null 字元數*/ padding-right: 4em; } button { width: 40px; height: 20px; font-size: 12px; padding: 0; outline: 0; position: absolute; right: 0; bottom: 0; }}