学习CSS伪类:before和:after

CSS中我们最熟悉也用得最多的伪类是:hover,今天为大家介绍2个新的伪类 :before 和 :after。
1. 基本语法
#example:before {
content: "#";
}
#example:after {
content: ".";
}有一点需要注意的是,如果你使用:before 和 :after,那么里面的content是可以留空的,但是不能不写,比如下面这样:
#example:before {
content: "";
display: block;
width: 100px;
height: 100px;
float: left;
}另外,在上面的CSS中都为伪类指定了生效的范围(类或ID),同时你可以把:before 和 :after写成全局性的,比如这样:
:before {
content: "#";
}2. 实例代码
<p class="box">Other content.</p>
p.box {
width: 300px;
border: solid 1px white;
padding: 20px;
}
p.box:before {
content: "#";
border: solid 1px white;
padding: 2px;
margin: 0 10px 0 0;
}p:before {
content: url(image.jpg);
}代码效果请看这里。
3. 该伪类的浏览器兼容性
- Chrome 2+,
- Firefox 3.5+ (只有部分功能在3.0中有效),
- Safari 1.3+,
- Opera 9.2+,
- IE8+ (会有一些小bug),
- 此外还兼容大部分手机浏览器.