普通文組 2.5

30天挑戰:「CSS 多行文字溢出後改為顯示刪節號」技術記錄

總結

text-overflow: ellipsis;僅能處理單行文字,若想要讓多行文字的尾端改為顯示刪節號,需使用-webkit-line-clamp

See the Pen text-overflow ellipsis by Charlie (@Charlie7779) on CodePen.

應用(卡片標題與內文):

效果展示

展示位置:https://tzynwang.github.io/ac_challenge_2-3F_profile-card/ 原始碼:https://github.com/tzynwang/ac_challenge_2-3F_profile-card

筆記

單行文字

MDN: The text-overflow property doesn’t force an overflow to occur. To make text overflow its container you have to set other CSS properties: overflow and white-space.

  • 務必搭配overflow: hidden;white-space: nowrap;

多行文字

MDN: It only works in combination with the display property set to -webkit-box or -webkit-inline-box, and the -webkit-box-orient property set to vertical.

MDN: In most cases you will also want to set overflow to hidden, otherwise the contents won’t be clipped but an ellipsis will still be shown after the specified number of lines.

  • -webkit-line-clamp需搭配display: -webkit-box;(或display: -webkit-inline-box;)與-webkit-box-orient: vertical;
  • -webkit-line-clamp的數值代表顯示在畫面上的行數
  • 最後補上overflow: hidden;text-overflow: ellipsis;來讓溢出的文字改顯示為刪節號;沒有設定overflow: hidden;的話,文字末端的刪節號還是會出現,但是超出-webkit-line-clamp的文字行也會跟著顯示出來

參考文件