css之多行文本輸出

css之多行文本輸出

需求

本小白拿着設計師給的帶標註的設計稿,看到簡介標註爲只能顯示3行文本,多於3行顯示3行,本準備採起字符串截取矇混過關(不能原諒的事情是對本身沒有要求,簡直沒有下限),後查看了網上的解決方案,特此分享。css

思路

如今假設想要顯示的文本行數是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) 乘以 [展開所有]按鈕的寬度)html

效果圖

圖片描述

完整代碼

<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)*尾部留空字符數]*/
    text-indent: -8em;
    /*尾部留空字符數*/
    padding-right: 4em;
  }
  button {
    width: 40px;
    height: 20px;
    font-size: 12px;
    padding: 0;
    outline: 0;
    position: absolute;
    right: 0;
    bottom: 0;
  }
}

參考實例

codepen實例web

相關文章
相關標籤/搜索