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;
}
<div class="parent">
<div class="float-left"></div>
<div style="clear: both"></div>
</div>
3. 父级定义伪类
.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
- position的值为absolute或fixed
.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;
}