伪元素选择器
选择器 | 作用 |
---|---|
::before | 在元素内部前面插入内容 |
::after | 在元素内部后面插入内容 |
注意:
- before和after必须有conttent属性
- before在内容得前面,after在内容得后面
- before和after创建一个元素,但是属于行内元素
- 因为在dom中看不见创建得元素,所以称之为伪元素
- 伪元素和标签选择器得权重 都为1
一个简单得案例
<!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>
div {
width: 300px;
height: 200px;
border: 1px solid #000;
}
div::before {
//content 后面是字符串 表示要添加得内容
content: "今天";
color: blue;
}
div::after {
content: "五";
color: red;
}
</style>
</head>
<body>
<div>星期</div>
</body>
</html>
给伪元素添加字体图标案例
<!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>
@font-face {
font-family: 'icomoon';
src: url('fonts/icomoon.eot?cv013x');
src: url('fonts/icomoon.eot?cv013x#iefix') format('embedded-opentype'), url('fonts/icomoon.ttf?cv013x') format('truetype'), url('fonts/icomoon.woff?cv013x') format('woff'), url('fonts/icomoon.svg?cv013x#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}
p {
position: relative;
width: 249px;
height: 30px;
border: 1px solid #000;
}
p::after {
font-family: "icomoon";
content: "";
font-size: 22px;
position: absolute;
top: 0;
right: 13px;
}
</style>
</head>
<body>
<p></p>
</body>
</html>
注意: content里面可以使用字体图标符号,用转义字符反斜扛()代替
content: "";
//这种伪元素也可以识别字体图标\
content: "\ea51"