before && after
1. 官方定义
2. 解释
3. 语法
.demo:before{
}
.demo:after{
}
4. 兼容性
IE | Edge | Firefox | Chrome | Safari | Opera | ios | android |
---|---|---|---|---|---|---|---|
all | all | all | all | all | all | all | all |
5. 实例
<div class="demo">网</div>
.demo:before{
content: '姓名:';
}
效果图:
- 在元素内容之后插入:很好。
.demo:after{
content: '很好';
}
效果图:
@H_502_430@
6. 经验分享
这两个伪类当然不是仅仅插入内容这么简单,它还有其他的妙用。
- 使用伪类 after 清除元素内部浮动效果:
<div class="demo">
<div class="item">慕</div>
<div class="item">课</div>
</div>
<div class="">网</div>
.demo:after{
content: '';
display: block;
clear: both;
}
.item{
float: left;
}
效果图:
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.demo:after{
content: '';
display: block;
clear: both;
}
.item{
float: left;
}
</style>
</head>
<body>
<div class="demo">
<div class="item">慕</div>
<div class="item">课</div>
</div>
<div class="">网</div>
</body>
</html>
<div class="demo">网</div>
.demo:before{
content: '';
display:inline-block;
width:px;
height:px;
font-size:px;
line-height:px;
background: url(//img.mukewang.com/wiki/5eea2f6809a8d35e00400040.jpg) center no-repeat;
background-size: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.demo:before{
content: '';
display:inline-block;
width:px;
height:px;
font-size:px;
line-height:px;
background: url(//img.mukewang.com/wiki/5eea2f6809a8d35e00400040.jpg) center no-repeat;
background-size: cover;
}
</style>
</head>
<body>
<div class="demo">网</div>
</body>
</html>
7. 小结
- 注意:对于 IE8 及更早版本中的
:before
、:after
,必须声明 <!DOCTYPE>。 - 在元素选择器后面这样写也可以:
.demo::before{
}
.demo::after{
}