:before和:after的使用方法
伪元素可以让我们很方便的加入一个样式,比如在字体前加一个icon,或者加一个下换线,可以不占一个元素的位置,使用起来也很方便,现在介绍一下使用的方法。
注意::before和:after中的content是必加项
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.test:before {
content: "《";
color:red
}
.test:after {
content: "》";
color:red
}
</style>
</head>
<body>
<div class="test">乔布斯自传</div>
</body>
</html>
首先我们自定义一个div的标签,然后添加类名,在样式中为
.test:before {
content:"《"
color:red
}
.test:after{
content:"》"
color:red
}
就会在前后出现一个书名号。
然后我们就会在这个elements中看到在元素的上下文中分别有一个::fefore和::after,注意是它没有在div的外边而是在元素的里面,它默认的是
d
i
s
p
l
y
:
i
n
l
i
n
e
−
b
l
o
c
k
(
但
是
我
们
尽
量
给
它
加
上
)
\color{red}{disply:inline-block(但是我们尽量给它加上)}
disply:inline−block(但是我们尽量给它加上) 所以是
《
乔
布
斯
传
》
\color{red}{《乔布斯传》}
《乔布斯传》 这样显示。
我们现在在代码中加上
d
i
s
p
l
y
:
b
l
o
c
k
\color{red}{disply:block}
disply:block
.test:before {
display: block;
content: "❤❤❤❤❤";
color: red;
}
.test:after {
display: block;
content: "❤❤❤❤❤";
color: red
}
这样就是上下加内容,因为它是display:block。这样使用的方法节省了我们的标签,用于在css渲染中向元素逻辑上的头部或尾部添加内容,这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入,所以不要用:before或:after展示有实际意义的内容,尽量使用它们显示修饰性内容,例如图标。