什么情况下需要清除浮动
- 以下图为例,fatherDiv想要被son1撑起
- 但这时的son1已经浮动了,所以这时时被son2撑起的
想要的效果
- fatherDiv被son1撑起
清除浮动的方式
设置clearfix:after,在父级元素上添加clearfix
.clearFix:after{
display:block;
content:'';
clear:both;
}
.clearFix {
zoom:1; 兼容ie
}
形成BFC
在父级元素上使用
display:inline-block- 或者
position:absolute - 或者
overflow:auto
代码实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>JS Bin</title>
<style>
.father {
width: 500px;
border: 3px solid green;
overflow:auto;
/* display:inline-block; */
/* position:absolute; */
}
.son1 {
width: 100px;
height: 100px;
border: 2px solid red;
color: red;
margin: 4px;
float: left;
}
.son2 {
color: blue;
border: 2px solid blue;
}
.bottomDiv {
width: 500px;
height: 100px;
margin: 5px 0;
border: 2px dotted black;
}
.clearfix:after {
display: block;
content: "";
clear: both;
}
</style>
</head>
<body>
<div class="father">
<div class="son1">
这是son1的内容,左浮动float left,本应该撑起父级元素
</div>
<div class="son2">
这是son2的内容,不进行浮动,没设置宽高,所以如果要撑起fatherDiv,就必须将son1清除浮动
</div>
</div>
<div class="bottomDiv">这是底部div的内容</div>
</body>
</html>