常见伪元素:
常见伪元素——::first-letter,::first-line,::before,::after,::selection。
其中::before和::after常用在项目中,巧妙的运用会会使很多样式的实现变得非常简单.
一般地,我们不去用::before和::after展示实际性的页面内容,多是修饰性的,像icon,角标,行标,还可以配合content清除浮动.
::before显示电话前的电话机icon:
<style type="text/css"> .phoneNumber::before { content:'\260E'; font-size: 15px; } </style>
</head>
<body>
<p class="phoneNumber">12345645654</p>
</body>
content属性:
::before和::after必须配合content属性来使用,content用来定义插入的内容 ,content可取以下值。
1 ) string
引号括起来的一段字符串,显示到当前元素的前后:
p::before{
content: "《";
}
p::after{
content: "》";
}
<p>平凡的世界</p>
//效果《平凡的世界》
2 ) attr()
通过attr()调用当前元素的属性,比如将图片alt提示文字或者链接的href地址显示出来。
<style> a::after{ content: "(" attr(href) ")"; } </style>
<a href="http://www.csdn.com/starof">博客地址</a>
//效果 博客地址(http://www.csdn.com/starof)
3 ) url()/uri()
用于引用媒体文件。
举例:“百度”前面给出一张图片,后面给出href属性。
<style> a::before{ content: url("https://www.baidu.com/img/baidu_jgylogo3.gif"); } a::after{ content:"("attr(href)")"; } a{ text-decoration: none; } </style>
---------------------------
<body>
<a href="http://www.baidu.com">百度</a>
</body>
### 4 ) counter()
调用计数器,实现章节序号功能。
<style> body { counter-reset: section; } h1 { counter-reset: subsection; } h2 { counter-reset: subsection; } h1:before { counter-increment: section; content: counter(section) "、"; } h2:before { counter-increment: subsection; content: counter(section) "." counter(subsection) "、"; } h3:before { counter-increment: subsection; content: counter(section) "." counter(section) "."counter(subsection) "、"; } </style>
</head>
<body>
<h1>大标题</h1>
<h2> 二副</h2>
<h2> 二副</h2>
<h2> 二副</h2>
<h3>  三副</h3>
<h3>  三副</h3>
<h3>  三副</h3>
</body>
运用
1、清除浮动
清除浮动方法有多种,现在最常用的就是下面这种方法,仅需要以下样式即可在元素尾部自动清除浮动
.cf:before,
.cf:after { content: " "; display: table; }
.cf:after { clear: both; }
.cf { *zoom: 1; }
2、float:居中
我们知道float没有center这个取值,但是可以通过伪类来模拟实现。
这个效果实现很有意思,左右通过::before float各自留出一半图片的位置,再把图片绝对定位上去。
3、做出各种图形效果
案例:六芒星
div做成三角形,将::after做成倒三角,绝对定位到div上
#star-six { width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 100px solid red; position: relative; }
#star-six::after{ width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-top: 100px solid red; position: absolute; content: ""; top: 30px; left: -50px; }
不了解CSS绘制图形的点这里→Shape of CSS
4、超链接特效
举例:配合 CSS定位实现一个鼠标移上去,超链接出现方括号的效果
a:hover::before, a:hover::after { position: absolute; }
a:hover::before { content: "\5B"; left: -10px; }
a:hover::after { content: "\5D"; right: -10px; }
常见的伪元素用法就说这么多,另外
附上一个有趣的连接:使用CSS3实现各类图形,效果满分