bfc的理解与应用
bfc的理解:
BFC是一个独立的块级渲染容器,拥有自己的渲染规则,不受外部影响,不影响外部特征
bfc特性:
- 内部box垂直往下排列
- 内部相邻块元素margin重叠,取较大的margin值
- BFC区域不会遮盖浮动元素区域
- 计算BFC高度时,浮动元素高度也计算在内
- BFC是独立渲染容器,外部元素不影响内部,反之亦然
bfc产生条件:
- 固定定位和绝对定位
- float除了none外
- overflow除了visible外(hidden、auto、scroll)
- display为以下其一(inline-block、table-cell、table-caption、flex)
bfc作用:
- 清除浮动(原理:bfc计算高度时,浮动元素也算在内)
<div class="box1-wrap">
<div class="box1">
<style>
.box1{
width: 100px;
height: 100px;
background-color: #bfc;
float: left;
}
/* 父元素开启bfc */
.box1-wrap{
border: 1px solid black;
overflow: hidden;
}
</style>
</div>
</div>
- 消除margin重叠两种情况:
- 父子元素嵌套垂直外边距重叠
<div class="box2-wrap">
<div class="box2">
<style>
/* 父元素开启bfc 根据实际情况选用不同的方式开启bfc*/
.box2-wrap{
width: 200px;
height: 200px;
background-color: #bfc;
margin-top: 100px;
overflow: hidden;
}
.box2{
width: 50px;
height: 50px;
background-color: black;
margin-top: 100px;
}
</style>
</div>
</div>
- 相邻块元素垂直margin重叠 取较大值
这个情况的解决办法要给其中一个元素加上父元素开启bfc 增加了html结构违背了编写html文档原理 不要为了解决问题添加无用的html标签
解决办法:只写一个元素的margin或尽量避免使用margin
<div class="box3"></div>
<div class="box4"></div>
<style>
.box3{
width: 100px;
height: 100px;
background-color: #bfc;
margin-bottom: 100px;
}
.box4{
width: 100px;
height: 100px;
background-color: pink;
margin-top: 200px;
}
</style>
- 布局(左浮动,右BFC自适应 避免右边元素区域与浮动元素重叠)