参考:https://zhuanlan.zhihu.com/p/25321647
https://blog.csdn.net/sinat_36422236/article/details/88763187
一、BFC 概念
BFC 即 Block Formatting Contexts (块级格式化上下文)
具有 BFC 特性的元素可以看作是隔离了的独立容器,容器里面的元素不会在布局上影响到外面的元素,并且 BFC 具有普通容器所没有的一些特性。
二、BFC的特点
1.同一个BFC下的非BFC元素在垂直方向的margin会折叠
<head>
div{
width: 100px;
height: 100px;
background: lightblue;
margin: 100px;
}
</head>
<body>
<div></div>
<div></div>
</body>
其中两个div都在body这一BFC下,所以两个div之间的距离只有100px,而不是200px。
要想让两个div的距离变成200px,只有把它们分别放入不同的BFC容器中才可以,直接将两个div变成BFC都没用。
2.浮动元素会使非BFC的父元素塌陷,但如果将父元素变成了BFC,就不会塌陷了
//坍陷
<div style="border: 1px solid #000;">
<div style="width: 100px;height: 100px;background: #eee;float: left;"></div>
</div>
//会包裹着浮动元素
<div style="border: 1px solid #000;overflow: hidden">
<div style="width: 100px;height: 100px;background: #eee;float: left;"></div>
</div>
3.BFC元素不会被浮动元素覆盖
//第一个div会覆盖第二个div的左上角,但不会覆盖其文本信息
<div style="height: 100px;width: 100px;float: left;background: lightblue">我是一个左浮动的元素</div>
<div style="width: 200px; height: 200px;background: #eee">我是一个没有设置浮动,
也没有触发 BFC 元素, width: 200px; height:200px; background: #eee;</div>
<div style="height: 100px;width: 100px;float: left;background: lightblue">我是一个左浮动的元素</div>
<div style="width: 200px; height: 200px;background: #eee;overflow: hidden">我是一个没有设置浮动,
触发了 BFC 元素, width: 200px; height:200px; background: #eee;</div>
给第二个div设置BFC之后,它会排在浮动元素的右侧,不会再被覆盖。
三、BFC的布局规则
1.内部的box会在垂直方向,一个接一个的放置
2.box垂直方向的距离有margin决定,相邻的margin会重叠
3.每个盒子(块盒与行盒)的margin box的左边,与包含块border box的左边相接触(对于从左往右的格式化,否则相反)。即使存在浮动也是如此。不会左右相邻。
4.BFC的区域不会与float box重叠。
5.BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也如此。
6.计算BFC的高度时,浮动元素也参与计算。
四、如何触发BFC
1、float的值不是none。
2、position的值不是static或者relative,是absolute、fixed。
3、display的值是inline-block、table-cell、flex、table-caption或者inline-flex。
4、overflow的值不是visible,是 hidden、auto、scroll。
5、body根元素。
网友评论