前端集合 - 关注前端技术和互联网免费资源

关注前端技术和互联网免费资源

分类儿

页面儿

搜索儿

前端集合 RSS订阅
Home » 前端集合 » 学习CSS伪类:before和:after

学习CSS伪类:before和:after

发布者:前端集合 // 发布时间:2011-07-14 22:27:52 // 分类:前端集合 // 访问: 3,769 次 // 热度:

image

Demo

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. 该伪类的浏览器兼容性

  1. Chrome 2+,
  2. Firefox 3.5+ (只有部分功能在3.0中有效),
  3. Safari 1.3+,
  4. Opera 9.2+,
  5. IE8+ (会有一些小bug),
  6. 此外还兼容大部分手机浏览器.

Tags: CSS, CSS伪类, :before, :after

我的手机编年史>>  << 用CSS 3制作的漂亮导航
Top