BCF(block formatting contex)块级格式化上下文内容 所谓的BFC就是css布局的一个概念,是一块区域,一个环境。
我们常说的文档流其实分为定位流、浮动流和普通流三种。而普通流其实就是指BFC中的FC。
FC是formatting context的首字母缩写,直译过来是格式化上下文,它是页面中的一块渲染区域,有一套渲染规则,决定了其子元素如何布局,以及和其他元素之间的关系和作用。
** BFC 可以简单的理解为某个元素的一个 CSS 属性,只不过这个属性不能被开发者显式的修改,拥有这个属性的元素对内部元素和外部元素会表现出一些特性,这就是BFC。**
触发bfc的条件
1.根元素,即HTML元素
2.float的值不为none
3.overflow的值不为visible
4.display的值为inline-block、table-cell、table-caption
5.position的值为absolute或fixed
BFC有哪些作用:
1.自适应两栏布局
2可以阻止元素被浮动元素覆盖
3可以包含浮动元素——清除内部浮动
4.分属于不同的BFC时可以阻止margin重叠
两个相邻的box 垂直方向 margin 会重和在一起
<body>
<div class="box1"></div>
<div class="main"></div>
</body>
<style>
*{
margin: 0;
padding: 0;
}
.box1{
width: 100px;
height: 100px;
background: pink;
margin-bottom:100px;
}
.main{
width:100px;
height: 100px;
background: yellow;
margin-top:100px;
}
</style>
按照我们原本的思路的话两个盒子的距离应该是200px 然而margin 垂直方向上只有100px的距离说明我们垂直方向距离重和了
2.bfc可以阻止margin 的重叠
<body>
<div class="box1"></div>
<div class="container">
<div class="main"></div>
</div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 100px;
height: 100px;
background: pink;
margin-bottom: 100px;
}
.main {
width: 100px;
height: 100px;
background: yellow;
margin-top: 100px;
}
.container {
overflow: hidden;
}
</style>
可以看见我们给 mian 添加一个父元素 触发bfc 让他们垂直方向的距离不重叠
3.子元素绑架了父元素的margin-top值
<body>
<div class="container">
<div class="main"></div>
</div>
</body>
* {
margin: 0;
padding: 0;
}
.container{
width: 200px;
height: 200px;
background: yellow;
}
.main {
width: 100px;
height: 100px;
background: red;
margin-top: 100px;
}
可以通过触发bfc 解决问题
<body>
<div class="container">
<div class="main"></div>
</div>
</body>
* {
margin: 0;
padding: 0;
}
.container{
width: 200px;
height: 200px;
background: yellow;
overflow:hidden;
}
.main {
width: 100px;
height: 100px;
background: red;
margin-top: 100px;
}
3.float元素不清楚浮动的话 会让一下个box重合
<body>
<div class="box"></div>
<div class="main"></div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
background: pink;
float: left;
}
.main {
width: 500px;
height: 200px;
background: red;
}
</style>
可以通过bfc 让 .main 不覆盖 解决重叠的问题
<body>
<div class="box"></div>
<div class="main"></div>
</body>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
background: pink;
float: left;
}
.main {
width: 500px;
height: 200px;
background: red;
overflow:hidden;
}
</style>
此种方法 可以左两栏自适应布局,以上就是bfc的一些用图 如有不足可以指出,感谢大家支持