不少小伙伴在防止高度坍塌时都会在浮动元素后面写入一个div,再在里面写入clear:both属性来清除浮动。那么今天就在此探究一下clear:both的工作原理。
先说一下clear:both的作用 -----不允许周围有浮动现象。
接下来直接上代码

<!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>#box {
height: 500px;
width: 1300px;
background-color: cornflowerblue;
float: right;
}

.father {
border: solid 1px pink;
}

.son1 {
width: 200px;
height: 200px;
background-color: powderblue;
float: left;
}

.son2 {

clear: both;

}</style>
</head>

<body>
<div class="father">
<div class="son1"></div>
<div class="son2"></div>
<div class="son3"></div>
</div>
</body>

</html>

在这里我们给son1加入了浮动,给son2清除了浮动。想而易见,效果就会变成这样

那么为什么在浮动元素后面的div加入clear:both属性就可以清除浮动呢。
按照定义,写入了clear both的元素不再允许周围有浮动的元素产生,所以son1对于Son2也就失去了浮动的效果,son1对于son2来说也就有了高度,son2就会位于son1的下面,son2的位置也就撑起了父级元素的高度,解决了高度坍塌的问题。