理解BFC

BFC:块格式化上下文(Block Formatting Context)

是Web页面的可视化CSS渲染的一部分,是布局过程中生成块级盒子的区域,也是浮动元素与其他元素的交互限定区域。

BFC 是一个独立的布局环境,可以理解为一个容器,在这个容器中按照一定规则进行物品摆放,并且不会影响其它环境中的物品

(如果一个元素符合触发 BFC 的条件,则 BFC 中的元素布局不受外部影响)

哪些条件会形成BFC?

1、浮动元素 float:left | right | inherit(none除外)
2、position:absolute 或 fixed 定位
3、display:inline-block | inline-flex | table-cell
4、overflow:hidden | auto | scroll (visible除外)

BFC的特性:

1、bfc 是一个独立的容器,容器内子元素不会影响容器外的元素
2、bfc的区域不会与float的元素区域重叠
3、计算bfc的高度时,浮动元素也参与计算
4、垂直方向上的距离由margin决定
5、内部的Box会在垂直方向上一个接一个的放置

栗子:

bfc的区域不会与float的元素区域重叠,使用overflow:hidden解决

<div class="column1"></div>
<div class="column2"></div>
.column1{
        width:200px;
        height:200px;
        margin-right:12px;
        background:orangered;
        float:left;
    }
    .column2{
        width:100%;
        height:200px;
        background:yellow;
       /* overflow:hidden;/*实现BFC*/
 }

使用overflow:hidden前和使用后

使用后

外边距重叠

<div class="outside">
    <div class="box1"></div>
    <div class="box2"></div>
</div>
    .outside{
        width: 100px;
        height: 100px;
        background: deeppink;
    }
    .box1{
        height:30px;
        margin:10px 0;
        background:orange;
    }
    .box2{
        height:30px;
        margin:30px 0;
        background:orange;
    }

由于垂直外边距会折叠,因此两个box盒子的垂直距离为30px而不是40px。

解决方法,把其中一个box放在另一个BFC容器里面

<div class="outside">
    <div class="box1"></div>
    <div class="content">
        <div class="box2"></div>
    </div>   
</div>
.content{
        overflow:hidden;
 }

内部的Box会在垂直方向上一个接一个的放置

<div class="container">
    <div class="item item1"></div>
    <div class="item item2"></div>
    <div class="item item3"></div>
    <div class="item item4"></div>
</div>
.container{
        /*position:absolute;/*实现BFC*/
        height:auto;
        background:gray;
    }
    .item{
        height:30px;
    }
    .item1{
        width:200px;
        background:deepskyblue;
    }
    .item2{
        width:100px;
        background:yellow;
        float:left;
    }
    .item3{
        width:300px;
        background:pink;
    }
    .item4{
        width:400px;
        background:brown;
    }

内部的Box会在垂直方向上一个接一个的放置,浮动的元素也是这样,box3浮动,他依然接着上一个盒子垂直排列。并且所有的盒子都左对齐

原文地址:https://www.cnblogs.com/theblogs/p/10455153.html