BFC的应用

概念:触发了BFC的盒子,盒子内部与外部完全隔离,容器内的子元素不会在布局上影响到外部的元素

一.产生BFC的方式:

1.overflow只要取值不是visible的情况

2.float的取值不为none的时候

3.display取值为table或者inline-block

4.position的取值是fixed或者absolute

二.常见的BFC的几种作用

1.当两个盒子,一个有margin-bottom属性,一个有margin-top属性,两个盒子的margin值会融合

<style>
    .box1{
    width: 200px;
    height: 200px;
    background-color: red;
    margin-bottom: 50px;    
    }
    .box2{
    width: 200px;
    height: 200px;
    background-color: lime;
    margin-top: 50px;    
    }
</style>

<div class="box1"></div>
<div class="box2"></div>

可以给其中一个盒子的父盒子添加BFC,添加BFC解决两个盒子margin值相互融合问题

<style>
    .box1{
    width: 200px;
    height: 200px;
    background-color: red;
    margin-bottom: 50px;    
    }
    .box2{
    width: 200px;
    height: 200px;
    background-color: lime;
    margin-top: 50px;    
    }
    .bfc{
        overflow: hidden;
    }
    </style>
    

<div class="box1"></div>

<div class="bfc">
<div class="box2"></div>
</div>

2.有两个盒子,一个父盒子,一盒子盒子,给子盒子设置margin-top值后,会将父盒子塌陷

给父盒子添加BFC,可以解决父盒子塌陷问题

<style>
.father{
    width: 200px;
    height: 200px;
    background-color: red;
    overflow: hidden;
}
.son{
    width: 100px;
    height: 100px;
    margin-top: 30px;
    background-color: lime;
}
</style>
    

<div class="father">
    <div class="son"></div>
</div>

3.BFC可以用来清除浮动

当子盒子浮动,元素拖标,不能撑开父盒子

给父盒子添加BFC

    <style>
.father{
    width: 300px;
    border: 1px solid #000;
    overflow: hidden;
}
.son{
    width: 200px;
    height: 200px;
    background-color: lime;
    float: left;
}
</style>
    

<div class="father">
    <div class="son"></div>
</div>

 4.触发了BFC的盒子,不会与浮动元素重叠  ,应用在左侧固定,右侧自适应布局中

<style>
.left{
width: 200px;
height: 200px;
background-color: red;
float: left;
}
.right{
height: 300px;
background-color: lime;
overflow: hidden;
}
</style>
    

<div class="left"></div>
<div class="right"></div>

猜你喜欢

转载自www.cnblogs.com/zhaodz/p/11571757.html
BFC
今日推荐