BFC - 应用场景

134 阅读1分钟

是什么

BFC是页面一块渲染范围,它有自己的渲染规则,因此会导致一系列页面布局问题

应用场景

1. margin重叠(塌陷)

同一个bfc里的盒子会发生margin合并现象,以最大为准

解决:将发生margin合并盒子外包裹一层容器,形成一块新的bfc

原:

<div class="box"></div>
<div class="box"></div>
.box{
    width: 50px;
    height: 50px;
    background-color: red;
    margin: 10px;
}

image.png

改:

<div class="box"></div>
<div class="container">
    <div class="box"></div>
</div>
.box{
    width: 50px;
    height: 50px;
    background-color: red;
    margin: 10px;
}
.container{
    overflow: hidden; //新bfc
}

image.png

2. 清除浮动(高度塌陷)

原:

<div class="container">
    <div class="box"></div>
    <div class="box"></div>
</div>
.container{
    width: 100%;
    background-color: bisque;
    padding: 10px;
}
.box{
    width: 50px;
    height: 50px;
    background-color: red;
    margin: 10px;
    float: left;
}

image.png

改: bfc计算高度时float元素高度也会加上

.container{
    overflow: hidden; //产生bfc
}

image.png

3. 自适应多栏布局

原:

<div class="aside"></div>
<div class="main"></div>
.aside{
    width: 30%;
    height: 200px;
    background-color: pink;
    float: left;
}
.main{
    width: 60%;
    height: 300px;
    background-color: red;
}

aside为浮动盒子,main的左边会与包含块左边向触

image.png

改: 触发main生成新的bfc,bfc不会与浮动重叠

.main{
    overflow: hidden;
}

image.png

小结

bfc实际就是一个独立的容器,里面子元素不影响外部