1 官方定义
块格式化上下文(Block Formatting Context,BFC) 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。
2 个人理解
每一个BFC区域只包括其子元素,不包括其子元素的子元素。
每一个BFC区域都是独立隔绝的,互不影响
3 触发bfc
- 根元素(<html>)
- 使用
float
时其浮动的元素 - 绝对定位的元素 (包含
position: fixed
或position: sticky
- 使用以下属性的元素
display: inline-block
- 表格单元格或使用
display: table-cell
, 包括使用display: table-*
属性的所有表格单元格 - 表格标题或使用
display: table-caption
的元素 - 块级元素的 overflow 属性不为
visible ---可能有副作用
- 元素属性为
display: flow-root
或display: flow-root list-item --- 无副作用
- 元素属性为
contain: layout
,content
, 或strict
- flex items
- 网格布局元素
- multicol containers
- 元素属性
column-span
设置为all
4 BFC特性
1、属于同一个BFC的两个相邻容器的上下margin会重叠
改为不是同一个bfc display: flow-root;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box { margin: 40px; background-color: aqua; } .bfc { display: flow-root; } </style> </head> <body> <div class="box">margin:40px</div> <div class="bfc"> <div class="box">margin:40px</div> </div> </body> </html>
2、计算BFC高度时浮动元素也参于计算
不给父节点设置高度,子节点设置浮动的时候,会发生高度塌陷,这个时候我们就要清除浮动。
吧父元素改为bfc
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box { border: 10px solid red; display: flow-root; } .son { float: left; width: 100px; height: 50px; border: 10px solid blueviolet; } </style> </head> <body> <div class="box"> <div class="son"></div> <div class="son"></div> <div class="son"></div> <div class="son"></div> </div> </body> </html>
3、BFC的区域不会与浮动容器发生重叠-可以左右布局
将right改为bfc
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box1 { width: 100px; height: 100px; float: left; background-color: aqua; } .box2 { height: 300px; background-color: blueviolet; display: flow-root; } </style> </head> <body> <div class="box1">left</div> <div class="box2">right</div> </body> </html>
4、BFC内的容器在垂直方向依次排列
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具