1 使用伪元素
1.1 首先我们得了解下伪元素是什么以及他的位置在哪
伪元素其实就是一个虚假的元素,我们在清除浮动的时候经常使用的是before与after这两个,他们分类在元素的内部最前边与最后的地方,我们可以同下边的代码查看他们的位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试伪元素 </title>
<style>
.box{
width: 130px;
height: 75px;
background-color: #ffcc00;
color: greenyellow;
opacity: 0.5;
}
.box:after {
content: "我是后边的伪元素";
color: red;
}
.box:before {
content: "我是前边的伪元素";
color: blue;
}
</style>
</head>
<body>
<div class="box">我是box中的内容</div>
</body>
</html>
1.2 没有清除前
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试清除浮动</title>
<style>
.box {
height: 100px;
width: 100px;
margin: 10px;
background-color: lightskyblue;
}
.fl{
float: left;
}
/* .outer:after { // 被注释掉了
display: block;
content: "";
clear: both;
}*/
.last {
background-color: orange;
}
</style>
</head>
<body>
<div class="outer">
<div class="box fl"></div>
<div class="box fl"></div>
</div>
<div class="box last"></div>
</body>
</html>
1.3 使用它来清除浮动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试清除浮动</title>
<style>
.box {
height: 100px;
width: 100px;
margin: 10px;
background-color: lightskyblue;
}
.fl{
float: left;
}
.outer:after { /*去掉注释*/
display: block;
content: "";
clear: both;
}
.last {
background-color: orange;
}
</style>
</head>
<body>
<div class="outer">
<div class="box fl"></div>
<div class="box fl"></div>
</div>
<div class="box last"></div>
</body>
</html>
伪元素的设置
.outer:after { /* :前的为要选择的元素*/
display: block;
content: "";
clear: both;
}