before和:after的作用就是在指定的元素内容(而不是元素本身)之前或者之后插入一个包含content属性指定内容的行内元素,最基本的用法如下:
#ex:before {
content:"#";
color:red;
}
#ex:after {
content:"$";
color:red;
}
这段代码会在#ex元素内容之前插入一个'#',以及在内容之后添加一个'$',插入的行内元素是作为#ex的子元素,效果如下:
如果没有content属性,伪类元素将没有任何作用。但是可以指定content为空,同时正如前面所说,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。
PS。浏览器支持情况
-
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不支持也应该能降级到正常显示主体内容。
PS。第二次,可以用这两个伪类做些有意思的小玩意儿哦~例如画个太极图~!
上码!:
#yin-yang {
width: 96px;
height: 48px;
background: #fff;
border-color: #000;
border-style: solid;
border-width: 2px 2px 50px 2px;
border-radius: 100%;
position: relative;
margin: 50px 200px;
}
#yin-yang:before {
content: "";
position: absolute;
top: 50%;
left: 0;
background: #eee;
border: 18px solid #000;
border-radius: 100%;
width: 12px;
height: 12px;
}
#yin-yang:after {
content: "";
position: absolute;
top: 50%;
right: 0;
background: #000;
border: 18px solid #fff;
border-radius: 100%;
width: 12px;
height: 12px;
}
效果图: