巧妙利用before和after伪类实现文字的展开和收起

需求:一段文字,当收起的时候,显示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值。就能够做到图例上的样子了。

posted @ 2014-11-10 15:14  hlily  阅读(7297)  评论(3编辑  收藏  举报