css3 伪元素选择器
伪元素选择器可以帮助我们利用css创建新标签元素,而不需要html标签,从而简化html结构,避免元素嵌套。
::before | 在元素内部的前面插入内容 |
---|---|
::after | 在元素内部的后面插入内容 |
注意:
-before和after创建的元素属于伪元素。
-由于是在文档书中是找不到的,是虚拟的,所以称为伪元素。
-before和arter必须有content属性。
-伪元素与标签选择器一样,权重为1。
-before和after都是行内块元素,不能直接设置大小。
语法:
E::before {
}
例子:
1.简单介绍用法
<!doctype html>
<html>
<head>
<meta charset='UTF-8' />
<title>damoe</title>
<style>
div {
width: 200px;
height: 50px;
background-color: bisque;
}
div::before {
content: "sss ";
}
div::after {
content: " ccc";
}
</style>
</head>
<body>
<div>xxx</div>
</body>
</html>
效果:
2.使用伪元素构建字体图标
<!doctype html>
<html>
<head>
<meta charset='UTF-8' />
<title>damoe</title>
<style>
div {
position: relative;
width: 200px;
height: 50px;
border: 2px solid rgb(250, 78, 78);
margin: 100px auto;
line-height: 50px;
font-size: 20px;
}
div::after {
content: '>';
position: absolute;
right: 5px;
color: rgb(250, 78, 78);
font-size: 25px;
}
</style>
</head>
<body>
<div>xxx</div>
</body>
</html>
效果:
3.使用伪元素做遮罩层
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>视频播放窗口</title>
<style>
.box {
position: relative;
width: 444px;
height: 320px;
margin: 100px auto;
background-color: aquamarine;
}
img {
width: 100%;
height: 100%;
}
.box::before {
content: '';
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, .4) url(imgs/arr.png) no-repeat center;
}
/* 鼠标经过box,box里面的隐藏层yincang显示出来 */
.box:hover::before {
/* 注意没有空格 */
display: block;
}
</style>
</head>
<body>
<div class="box">
<img src="imgs/pic.png">
</div>
</body>
</html>
效果:
鼠标经过时:
4.伪元素清除浮动
额外标签法,也叫做隔墙法,要求标签为块级元素。
<!doctype html>
<html>
<head>
<meta charset='UTF-8' />
<title>damoe</title>
<style>
.f {
background-color: indigo;
}
.s,
.t {
float: left;
width: 200px;
height: 200px;
background-color: indianred;
}
.f::before,
.f::after {
content: "";
/* 转化成块 */
display: block;
height: 0;
clear: both;
visibility: hidden;
}
</style>
</head>
<body>
<div class="f">
<div class="s"> xxx</div>
<div class="t">sss</div>
</div>
</body>
</html>
效果: