before && after这两个伪类元素功能很相似,都是在元素内部插入新的内容。下面一起看下他们的区别和用法。 1. 官方定义before:元素的内容之前插入新内容。 2. 解释before 和 after 的功能就是在元素的内部的原有内容之前,或者之后插入新的内容。 3. 语法.demo:before{
}
.demo:after{
}解释:使用方法如上面,通过在元素选择器后面增加一个 : 来开始伪类的使用。 4. 兼容性
5. 实例<div class="demo">网</div>
.demo:before{
content: '姓名:';
}效果图:
<!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>@H_417_301@
.demo:before{
content: '姓名:';
}
</style>
</head>
<body>
<div class="demo">网</div>
</body>
</html>
.demo:after{
content: '很好';
}效果图:
<!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>@H_417_301@
.demo:after{
content: '很好';
}
</style>
</head>
<body>
<div class="demo">网</div>
</body>
</html>6. 经验分享这两个伪类当然不是仅仅插入内容这么简单,它还有其他的妙用。
<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>@H_417_301@
.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>@H_417_301@
.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. 小结
.demo::before{
}
.demo::after{
} |