css伪类(:before和:after)

:before和:after的作用就是在指定的元素内容(而不是元素本身)之前或者之后插入一个包含content属性指定内容的行内元素,最基本的用法如下:

#example{
   width:300px;
   height:40px;
   line-height:40px;
   border:1px solid #e2e2e2;
   margin-top:100px;
   margin-left:100px;
   text-align:center;
 }
#example:before {
    content: "#";
    color: #f6f;
}
#example:after {
    content: "$";
    color: red;
}
这段代码会在#example元素内容之前插入一个'#',以及在内容之后添加一个'$',插入的行内元素是作为#example的子元素,效果如下:
 需要注意的是如果没有content属性,伪类元素将没有任何作用。但是可以指定content为空,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。
 
#example:before {
     content: "";
     display: block;
     width: 100px;
     height: 100px;
}
 
伪类元素也会像其他子元素一样正常继承父元素的一些CSS属性,比如字体等。
 
 
posted @ 2018-06-23 19:25  _小狐狸  阅读(3150)  评论(0编辑  收藏  举报