这两个伪类元素功能很相似,都是在元素内部插入新的内容。下面一起看下他们的区别和用法。
before:元素的内容之前插入新内容。
after:元素的内容之后插入新内容。
before
和 after
的功能就是在元素的内部的原有内容之前,或者之后插入新的内容。
.demo:before{
}
.demo:after{
}
解释:使用方法如上面,通过在元素选择器后面增加一个 :
来开始伪类的使用。
IE | Edge | Firefox | Chrome | Safari | Opera | ios | android |
---|---|---|---|---|---|---|---|
all | all | all | all | all | all | all | all |
<div class="demo">xx网</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> .demo:before{ content: '姓名:'; } </style>
</head>
<body>
<div class="demo">xx网</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> .demo:after{ content: '很好'; } </style>
</head>
<body>
<div class="demo">xx网</div>
</body>
</html>
这两个伪类当然不是仅仅插入内容这么简单,它还有其他的妙用。
<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">xx网</div>
.demo:before{
content: '';
display:inline-block;
width:12px;
height:12px;
font-size:12px;
line-height:12px;
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:12px; height:12px; font-size:12px; line-height:12px; background: url(//img.mukewang.com/wiki/5eea2f6809a8d35e00400040.jpg) center no-repeat; background-size: cover; } </style>
</head>
<body>
<div class="demo">xx网</div>
</body>
</html>
:before
、:after
,必须声明 <!DOCTYPE>。.demo::before{
}
.demo::after{
}
0/1000