关于伪类元素:before和:after

来源:互联网 发布:informix查询序列sql 编辑:程序博客网 时间:2024/05/06 02:46

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

#example:before {    content: "#";    color: red;}#example:after {    content: "$";    color: red;}

这段代码会在#example元素内容之前插入一个'#',以及在内容之后添加一个'$',插入的行内元素是作为#example的子元素,效果如下:

Here is the example content

需要注意的是如果没有content属性,伪类元素将没有任何作用。但是可以指定content为空,同时正如前面所说,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。

#example:before {    content: "";    display: block;    width: 100px;    height: 100px;}

伪类元素也会像其他子元素一样正常继承父元素的一些CSS属性,比如字体等。

除了插入文字内容,还可以指定其他内容:

p:before {    content: url('img.jpg');}a:after {    content: attr(href);}

attr()函数会返回指定元素对应属性的值

最后,奉上最惦记的浏览器支持情况

  • Chrome 2+,
  • Firefox 3.5+ (3.0 had partial support),
  • Safari 1.3+,
  • Opera 9.2+,
  • IE8+ (with some minor bugs),
  • Pretty much all mobile browsers.

放在伪类元素里面的内容一般都只是装饰性的,所以即便是IE6/7不支持也应该能降级到正常显示主体内容。

:before和:after的一些惊人用法

>. clearfix hack

如果父元素容器里面的子元素是浮动元素的话,我们一般需要在父元素闭合前添加一个clear:both的元素用于清除浮动从而能使父容器正常被子元素内容撑起,但是这种方法引入了多余的无意义标签,并且有javascript操作子元素的时候容易引发bug。一种更好的方法是利用CSS,所以在一些CSS文件中经常会看到类似于.clearfix这样的类出没,只要在父容器上应用这个类即可实现清除浮动。下面是利用:before和:after的一个实现:(viaNicolas 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;}

资源链接

  • Learning To Use The :before And :after Pseudo-Elements In CSS
  • The Shapes of CSS
  • Pseudo-elements reference
  • Add steps counter in form via CSS
原文地址:http://www.hulufei.com/post/about-before-and-after-pseudo-element
0 0
原创粉丝点击