对BFC的理解
BFC全称为 block formatting context, 块级格式化上下文. 它是一个独立的渲染区域, 区域内的元素不会在布局影响到外部元素.
例如: 两个元素上下margin重叠, 则需要对两个元素实现BFC, 使得两个元素样式互不干扰等等
如何触发BFC?
- 根元素()
- 浮动元素 (float 不是none)
- 绝对定位元素 (position为absolute或fixed)
- display为 inline-block、table-cell、table-caption、table、table-row、table-row-group、table-header-group、table-footer-group、inline-table、flow-root、flex、inline-flex、grid、inline-grid
- overflow值不会visible的块元素
- contain值为layout、content、paint的元素
- 多列容器 (元素的column-count或column-width不为auto, 包括column-count为1)
BFC 特性与作用
- 避免外边距重叠
将两个元素放置不同的BFC里<div class='container'> <div class='box'></div> </div> <div class='container'> <div class='box'></div> </div> .container { overflow: hidden; } .box { width: 100px; height: 100px; background: red; margin: 100px; }
- 避免父元素高度塌陷
给父元素加上BFC,清除浮动<div class='container'> <div class='box'></div> </div> .container { border: 1px solid red; overflow: hidden; } .box { width: 100px; height: 100px; background: blue; margin: 100px; float: left }
- 阻止元素被浮动元素覆盖
触发正常元素的BFC属性<div class='floatDiv'></div> <div class='normalDiv'></div> .floatDiv { width: 100px; height: 100px; background: blue; float: left; } .normalDiv { width: 200px; height: 200px; background: red; overflow: hidden; }