方法1:
浮动元素后添加新元素,设置width:0;height:0;overflow:hidden;clerar:both;
方法2:
盒子设置overflow:auto;zoom:1;
ps:zoom属性是IE浏览器特有的一个属性,它的原本功能是设置或检测对象的缩放比例,此处可用来兼容IE低版本清除浮动原理为触发IE的haslayout 来清除浮动
方法3:
通过::after为盒子追加伪元素,并设置伪元素相关属性;
方法4:
盒子设置display:inline-block;
ps:margin左右居中失效
方法5:
盒子设置浮动
案例代码如下:
<!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>清楚浮动</title>
</head>
<style>
*{
margin:0;
padding:0;
}
.box,.box1,.box2,.box3,.box4,.box5{
width:400px;
margin:50px auto;
background: rgb(218, 180, 14);
position: relative;
}
.item,.item1,.item2,.item3,.item4,.item5{
width:80px;
height:80px;
float:left;
opacity: 0.4;
}
p{
width:50px;
height:50px;
background: yellowgreen;
}
span{
position: absolute;
top:0;
right:0;
}
.item{
background: #000;
}
.item1{
background:yellow;
}
.item2{
background: green;
}
.item3{
background: blue;
}
.item4{
background: red;
}
.item5{
background: blueviolet;
}
/*
方法1:添加新元素,设置width:0;height:0;overflow:hidden;clerar:both;
*/
.box1 p{
clear:both;
overflow: hidden;
}
/*
方法2:盒子设置overflow:auto;zoom:1;
*/
.box2{
overflow:auto;
zoom:1;
}
/*
方法3:通过::after伪元素
*/
.box3::after{
display:block;
content:'.';
width:0;
height:0;
visibility:hidden;
clear:both;
}
/*
方法4:盒子设置display:inline-block;
*/
.box4{
display: inline-block;
}
/*
方法4:盒子设置浮动
*/
.box5{
float:left
}
</style>
<body>
<div class="box">
<span>未清除浮动</span>
<div class="item"></div>
<p></p>
</div>
<div class="box1">
<span>方法1</span>
<div class="item1"></div>
<p></p>
</div>
<div class="box2">
<span>方法2</span>
<div class="item2"></div>
<p></p>
</div>
<div class="box3">
<span>方法3</span>
<div class="item3"></div>
<p></p>
</div>
<div class="box4">
<span>方法4</span>
<div class="item4"></div>
<p></p>
</div>
<div class="box5">
<span>方法5</span>
<div class="item5"></div>
<p></p>
</div>
</body>
</html>
效果日下图:
总结:
1. 方法1效果将浮动元素视为普通文本流;
2. 方法2、方法3、方法4、方法5只是使浮动元素被盒子所识别并计算高度,但依然保留非普通文本流特性;
3. 方法4、方法5会使margin属性受到影响