装载于:详细用法请参考原文
一、介绍
- css3为了区分伪类和伪元素,伪元素采用双冒号写法。
- 常见伪类——:hover,:link,:active,:target,:not(),:focus。
- 常见伪元素——::first-letter,::first-line,::before,::after,::selection。
-
::before和::after下特有的content,用于在css渲染中向元素逻辑上的头部或尾部添加内容。
-
这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入。
-
所以不要用:before或:after展示有实际意义的内容,尽量使用它们显示修饰性内容,例如图标。
二、content属性
::before和::after必须配合content属性来使用,content用来定义插入的内容,content必须有值,至少是空。默认情况下,伪类元素的display是默认值inline,可以通过设置display:block来改变其显示。
content可取以下值。
1、string
使用引号包一段字符串,将会向元素内容中添加字符串。如:a:after{content:""}
<!DOCTYPE html>
<meta charset="utf-8" />
<style type="text/css">
p::before{
content: "《";
color: blue;
}
p::after{
content: "》";
color: blue;
}
</style>
<p>平凡的世界</p>
效果:《平凡的世界》
2、attr()
通过attr()调用当前元素的属性,比如将图片alt提示文字或者链接的href地址显示出来。
<style type="text/css">
a::after{
content: "(" attr(href) ")";
}
</style>
<a href="http://www.cnblogs.com/starof">starof</a>
效果:http://www.cnblogs.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.做出图形效果(常用)
举例:一个六角星
<style>
#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;
}
</style>
<body>
<div id="star-six"></div>
</body>
实现原理:
#star-six的div是一个正三角行,#star-six::after是一个倒三角形,通过绝对定位,调整其位置即可实现六角星的效果。
举例:" + “和” - "
button.accordion:after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
button.accordion.active:after {
content: "\2212";
}