Open YBFACC opened 4 years ago
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
以下设置会产生BFC
<html>
float
none
position
absolute
fixed
display
inline-block
overflow
visible
flex
inline-flex
grid
inline-grid
column-count
column-width
auto
column-coun
1
以上引用来自MDN
我们可以知道根元素<html>就是一个 BFC。当我们在页面中开启新的BFC,这就像在在旧 Html 中,开启了一个新的 Html 。这两个 Html 不能相互影响。
根元素<html>
<div id="div_1" class="BFC"> <div id="div_2"> <div id="div_3"></div> </div> <div id="div_4"> <div id="div_5"></div> </div> <div id="div_6" class="BFC"> <div id="div_7"></div> <div id="div_8"></div> </div> </div>
<style> .box { border: 10px solid red; } .left { width: 50px; height: 50px; background-color: aqua; float: left; } </style> <body> <div class="box"> <div class="left"></div> </div> </body>
经典的高度塌陷。想解决它,利用上面的属性1。我们给 .box 添加上 overflow: hidden; 来开启BFC
.box
overflow: hidden;
<style> .box1 { height: 100px; width: 100px; float: left; background: lightblue; } .box2 { width: 200px; height: 200px; background: #eee; } </style> <body> <div class="box1">左浮动</div> <div class="box2">awecscrsc dadaedaed adaedaedadaedewdrgvr vcercrcwcnciwenciwen wcwinciweicmweomcowe </div> </body>
可以看到这里的 box1 出现了环绕的效果。这里清除前一个浮动的影响,可以使 box2 开启 BFC。
box1
box2
<style> .box1 { height: 100px; width: 100px; background: lightblue; margin: 50px; } .box2 { width: 100px; height: 100px; background: #eee; margin: 50px; } </style> <body> <div class="box1"></div> <div class="box2"></div> </body>
可以看到这里上下边距出现了重叠。解决此方法可以给 box2 套一层 wrap。
<style> .box1 { height: 100px; width: 100px; background: lightblue; margin: 50px; } .box2 { width: 100px; height: 100px; background: #eee; margin: 50px; } .wrap { overflow: hidden; } </style> <body> <div class="box1"></div> <div class="wrap"> <div class="box2"></div> </div> </body>
块格式化上下文
深入理解BFC
学习 BFC (Block Formatting Context)
BFC
介绍
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
以下设置会产生BFC
<html>
)float
不是none
)position
为absolute
或fixed
)display
为inline-block
)overflow
值不为visible
的块元素display
为flex
或inline-flex
元素的直接子元素)display
为grid
或inline-grid
元素的直接子元素)column-count
或column-width
不为auto
,包括column-coun
为1
)以上引用来自MDN
我的理解
我们可以知道
根元素<html>
就是一个 BFC。当我们在页面中开启新的BFC,这就像在在旧 Html 中,开启了一个新的 Html 。这两个 Html 不能相互影响。BFC的范围
使用
测试
高度塌陷
经典的高度塌陷。想解决它,利用上面的属性1。我们给
.box
添加上overflow: hidden;
来开启BFC清除前一个浮动的影响
可以看到这里的
box1
出现了环绕的效果。这里清除前一个浮动的影响,可以使box2
开启 BFC。外边距折叠
可以看到这里上下边距出现了重叠。解决此方法可以给
box2
套一层 wrap。参考
块格式化上下文
深入理解BFC
学习 BFC (Block Formatting Context)