您现在的位置:首页 >> 前端 >> 内容

CSS伪元素before和after

时间:2014/4/28 9:01:52 点击:

  核心提示:今天发现很多国外的网站和框架设计都用到了before和after,之前使用的比较少,今天试了下觉得还是很有意思的~说明1. :before 和 :after将在内容元素的前后插入额外的元素;:befo...
今天发现很多国外的网站和框架设计都用到了before和after,之前使用的比较少,今天试了下觉得还是很有意思的~

 

说明

 

1. :before 和 :after将在内容元素的前后插入额外的元素;:before将会在内容之前“添加”一个元素而:after将会在内容后“添加”一个元素。在它们之中添加内容我们可以使用content属性。

 

2. :before 和 :after发布于CSS2.1, 在css3中修订后伪元素使用::,伪类使用:, 因而形式为:: before, ::after

 

3. 无论使用单引号还是双引号浏览器都能识别,但是IE8只支持单冒号格式,因而为兼容还是使用单冒号

 

 

 

简单例子

 

    .p1:before{

        content:open-quote;

    }

    .p1:after{

        content:close-quote;

    }

    <p class="p1"> Today is a wonderful day. Wish you happy~</p>

结果:

 

“ Today is a wonderful day. Wish you happy~”

 

 

设置伪元素样式

 

eg1:

 

    .p1{

        width:500px;

        height:200px;

        margin:100px auto;

        background-color:#F0F0F0;

        line-height:200px;

        text-align:center;

    }

     .p1:before{

        content:open-quote;

        position:relative;

        font-size: 24pt;

        line-height:200px;

        text-align:center;

        color:#fff;

        background:#ddd;

        border-radius:25px;

        

    }

    .p1:after{

        content:close-quote;

        position:relative;

        font-size: 24pt;

        background:#ddd;

        border-radius:25px;

        line-height:200px;

        text-align:center;

        color:#fff;

    }

 

    <p class="p1"> Today is a wonderful day. Wish you happy~</p>

结果:

 

 

 

注意:实际使用时注意将相同的css抽取,p[class*='']:before, p[class*='']:after 

 

eg2:(与伪类结合使用)

 

添加样式:

 

    .p1:hover:after,.p1:hover:before {

         background-color: #555;

        }

 

 

Tags:CS SS S伪 伪元 
作者:网络 来源:不详