1. 给父级定义height
.parent {
background-color: red;
}
.float-left {
width: 200px;
height: 200px;
float: left;
}
<div class="parent">
<div class="float-left"></div>
</div>
2. 在结尾处添加空div,样式设置为clear: both
.parent {
background-color: red;
}
.float-left {
width: 200px;
height: 200px;
float: left; //这里clear的作用是清除浮动,它需要跟在浮动元素的后面
}
<div class="parent">
<div class="float-left"></div>
<div style="clear: right"></div>
<!-- 这里clear的作用是清除浮动,它需要跟在浮动元素的后面,left为清除左浮动,right为清除右浮动,both为清除全部 -->
</div>
3. 父级定义伪类
"clearfloat"是父容器的class名称,“content:” ";"是在父容器的结尾处放一个空白字符,"height:0;"是让这个这个空白字符不显示出来,"display: block; clear: both;"是确保这个空白字符是非浮动的独立区块。但是,:after选择符IE 6不支持,也就是说上面的这段代码在IE 6中无效,这怎么办? 我们添加一条IE6的独有命令"zoom:1;"就行了,这条命令的作用是激活父元素的"hasLayout"属性,让父元素拥有自己的布局。IE 6会读取这条命令,其他浏览器则会直接忽略它。
.parent {
background-color: red;
}
.float-left {
width: 200px;
height: 200px;
float: left;
}
.clearfloat:after {
display: block;
clear: both;
content: '';
visibility: hidden;
height: 0;
zoom: 1;
}
<div class="parent clearfloat">
<div class="float-left"></div>
</div>
4. 把父级变成BFC
生成BFC的条件
- 根元素
- float的值不为none
- overflow的值不为visible
- display的值为inline-block、table-cell、table-caption
- column-span: all
- position的值为absolute或fixed
- 弹性盒(flex或inline-flex)
- display: flow-root
.parent {
background-color: red;
float: left;
}
.parent {
background-color: red;
overflow: hidden;
}
.parent {
background-color: red;
display: table-cell;
}
.parent {
background-color: red;
position: absolute;
}