BFC规范

时间:2023-12-23 08:24:26

BFC规范

BFC规范是什么?

BFC规范也叫块级格式化上下文。是指一个独立的容器。

如何触发BFC?

我们可以通过一下几种方式触发BFC

1.通过浮动触发:float(除none)

2.通过绝对\固定定位触发:position:absolute\flxed

3.通过display触发:display:inline-block\flex\table-cells

4.通过overflow触发:overflow:hidden\auto\scroll

什么时候需要触发BFC?

1、上下块级元素的margin相叠加的时候。

style:
.box1{
width: 300px;
height: 200px;
background: red;
margin:20px 0;
}
.box2{
width: 300px;
height: 200px;
background: blue;
margin:50px 0;
}
.box{
overflow: hidden;
} html:
<div class="box">
<div class="box1"></div>
</div>
<div class="box">
<div class="box2"></div>
</div>

2、解决margin传递问题

style:
.box1{
background: red;
border:1px solid #ccc;
overflow: hidden;
}
.box2{
width: 300px;
height: 100px;
background: blue;
margin-top:50px;
float: left;
} html:
<div class="box1">
<div class="box2"></div>
</div>

3.解决浮动问题

style:
.box1{
background: red;
border:1px solid #ccc;
overflow: hidden;
}
.box2{
width: 300px;
height: 100px;
background: blue;
float: left;
} html:
<div class="box1">
<div class="box2"></div>
</div>

4、解决覆盖问题

style:
.box1{
background: red;
width: 300px;
height: 100px;
border:1px solid #ccc;
float: left;
}
.box2{
overflow: hidden;
height: 300px;
background: blue;
} html:
<div class="box1"></div>
<div class="box2">154545</div>

可以实现左边固定,右边自适应的两栏布局。