:before和:after的做用就是在指定的元素内容(而不是元素自己)以前或者以后插入一个包含content属性指定内容的行内元素,最基本的用法以下:javascript
#example:before { content: "#"; color: red; } #example:after { content: "$"; color: red; }
这段代码会在#example元素内容以前插入一个'#',以及在内容以后添加一个'$',插入的行内元素是做为#example的子元素,效果以下:java
Here is the example content浏览器
须要注意的是若是没有content属性,伪类元素将没有任何做用。可是能够指定content为空,同时正如前面所说,插入的内容默认是一个行内元素,而且在HTML源代码中没法看到,这就是为何称之为伪类元素的理由,因此也就没法经过DOM对其进行操做。函数
#example:before { content: ""; display: block; width: 100px; height: 100px; }
伪类元素也会像其余子元素同样正常继承父元素的一些CSS属性,好比字体等。post
除了插入文字内容,还能够指定其余内容:字体
p:before { content: url('img.jpg'); } a:after { content: attr(href); }
attr()函数会返回指定元素对应属性的值url
最后,奉上最惦记的浏览器支持状况code
放在伪类元素里面的内容通常都只是装饰性的,因此即使是IE6/7不支持也应该能降级到正常显示主体内容。继承
>. clearfix hackip
若是父元素容器里面的子元素是浮动元素的话,咱们通常须要在父元素闭合前添加一个clear:both的元素用于清除浮动从而能使父容器正常被子元素内容撑起,可是这种方法引入了多余的无心义标签,而且有javascript操做子元素的时候容易引起bug。一种更好的方法是利用CSS,因此在一些CSS文件中常常会看到相似于.clearfix这样的类出没,只要在父容器上应用这个类便可实现清除浮动。下面是利用:before和:after的一个实现:(via Nicolas Gallagher)
/* For modern browsers */ .clearfix:before, .clearfix:after { content:""; display:table; } .clearfix:after { clear:both; } /* For IE 6/7 (trigger hasLayout) */ .clearfix { zoom:1; }
>. CSS实现的八卦图案
#yin-yang { width: 96px; height: 48px; background: #eee; border-color: red; border-style: solid; border-width: 2px 2px 50px 2px; border-radius: 100%; position: relative; } #yin-yang:before { content: ""; position: absolute; top: 50%; left: 0; background: #eee; border: 18px solid red; border-radius: 100%; width: 12px; height: 12px; } #yin-yang:after { content: ""; position: absolute; top: 50%; left: 50%; background: red; border: 18px solid #eee; border-radius:100%; width: 12px; height: 12px; }
【原文】http://www.hulufei.com/post/about-before-and-after-pseudo-element