需求:一段文字,當收起的時候,顯示4行,並且多余4行的部分用省略號表示,關鍵是在省略號前面留有空白部分來放一些圖標等東西;展開的時候,全部顯示。
例如下面的示例圖:
收起的時候:
展開的時候:
在不用JS的情況下,如何能只用CSS就做到呢?
(一)先看下html結構
<div class="summary" data-content="天空為什么是藍色×××"><p class="content">天空為什么是藍色×××</p></div>
(二)再看下神奇的css
html,body,p{margin:0;padding: 0} .summary{ position: relative; overflow: hidden; margin-bottom: 5px; line-height: 22px; word-break: break-all; text-indent:5em; } .packup p{ height: 90px; } .packup:before{ display: block; content: attr(data-content); position: absolute; z-index: 1; left: 0; top: 0; height: 66px;//這里的高是3×22的結果,其中22是行高 ,3是4-1 width: 100%; overflow: hidden; color: #000; background-color: #fff; text-indent: 5em; } .packup:after{ display: -webkit-box; -webkit-box-orient: vertical; -webkit-box-sizing: border-box; box-sizing: border-box; -webkit-line-clamp: 4;//4就是需要在收起的時候顯示的行數 content: attr(data-content); position: absolute; left: 0; top: 0; width: 100%; height: 100%; text-indent: -4em; padding-right: 3em; color: #000; background-color: #fff; }
關鍵的思路就是:用before顯示的3行文字蓋在after的文字上(before有個背景色,並且height很重要);用after顯示4行文字,並且after的右邊padding-right一定的距離,使得省略號的右邊能夠空出一定的位置。
在收起的時候,給summary加上packup的class值;在展開的時候,去掉summary上的packup這個class值。就能夠做到圖例上的樣子了。