-
BFC : Block Formatting Context
块级格式化上下文,一个 触发BFC规范的元素,可以形成一个独立的容器,不受到外界影响
触发BFC方式
- 浮动元素float:除了none
- 绝对定位元素: position: absolute fixed
- display为inline-block table-cells flex
- overflow除了visible以外的值(hidden auto scroll)
BFC应用
1 解决margin叠加问题(并列元素
<style>
.box1{ width: 100px;height:100px;background-color: red;margin-bottom: 10px;}
.box2{width: 100px;height: 100px;background-color: blue ;margin-top: 10px;}
</style>
<div class="box1"></div>
<div class="box2"></div>
在margin-bottom和margin-top之间只取最大的值10px
解决方法
1只设置margin-bottom或者只设置margin-top
2在外层裹一个BFC
<style>
.box{overflow: hidden}
.box1{ width: 100px;height:100px;background-color: red;margin-bottom: 10px;}
.box2{width: 100px;height: 100px;background-color: blue ;margin-top: 10px;}
</style>
<div class="box">
<div class="box1"></div>
</div>
<div class="box2"></div>
2 margin叠加问题(嵌套盒子)
内部盒子的margin-top会影响外部盒子,内部小蓝色盒子margin-top: 200px;使得外部红色盒子也移动了(其实也在和外部的margin-top取最大值)
解决办法,外部盒子加上BFC overflow:hidden
3 解决浮动父元素问题 float
父元素没有设置height,想让子元素把它撑开,但是当子元素浮动后,脱离文档流,无法将父元素撑开
所以要给父元素加个overflow:hidden来触发BFC,变成下面这样
4 解决浮动中兄弟元素问题 float
红色方块float之后,会脱离文档流,压在蓝色方块上方,但是红色方块不会盖住蓝色方块上的文字,因为文字默认提升半层
为了不影响蓝色方块中的内容,让蓝色方块触发BFC
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box1{width: 100px;height:100px;background-color: red;float: left}
.box2{height: 300px;background-color: blue;overflow: hidden}
/*不要设置width */
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2">这里是BOX2</div>
</body>
</html>
如果box2设置的是overflow:hidden那么它的宽度将占据所有空余宽度
但是如果box2设置的是float:left那么它的宽度将由内容决定
如果设置了width:100%(无论float还是overflow),均会如下图所示