3. 解决方案
主要根据BFC的原理实现,因为BFC的渲染的是整块区域,也就会计算出宽、高。这也是传说中的清除浮动的方案
3.1 父容器创建BFC方法
3.1.1 创建BFC的方法
a) Float除了none以外的取值;
b) Overflow除了visible以外的值;
c) Display值为table-cell、table-caption、inline-block、flex、inline-flex等
d) Position值为absloute、fixed
e) Fieldset元素
3.1.2 清除浮动
a) Float、overflow、display三种方式都可以清除浮动,但position、fieldset虽然创建了bfc但不可以清除浮动(也就是不能解决高度塌陷的问题)。主要原因为:position、fieldset都需要子元素来撑开父容器的高度,但子元素浮动后又不存在高度,所以失效。
b) Float、overflow、display示例代码:
.wrap{
background: gray;
padding: 10px;
overflow: auto;
}
.left, .right{
background: red;
float: left;
width: 200px;
height: 100px;
}
.right{
background: yellow;
}
.footer{
background: pink;
}
<div class="wrap" >
<div class="left">left</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>
3.1.3 最后一个子元素clear:both
利用clear:both触发父容器重新计算高度的原理实现,示例代码如下:
.wrap{
background: gray;
padding: 10px;
}
.left, .right{
background: red;
float: left;
width: 200px;
height: 100px;
}
.right{
background: yellow;
}
.footer{
background: pink;
}
.clear{
clear: both;
zoom: 1;
}
<div class="wrap" >
<div class="left">left</div>
<div class="right">right</div>
<div class="clear"></div>
</div>
<div class="footer">footer</div>3.1.4 After添加最后一个子元素
利用css的:after伪元素实现,动态插入元素并清除浮动:
.wrap{
background: gray;
padding: 10px;
}
.wrap:after{
content: '';
display: block;
overflow: hidden;
clear: both;
}
.left, .right{
background: red;
float: left;
width: 200px;
height: 100px;
}
.right{
background: yellow;
}
.footer{
background: pink;
}
<div class="wrap" >
<div class="left">left</div>










