1、什么是块级格式上下文?
BFC是一块独立的渲染区域,它规定了在该区域中,常规流块级盒子的布局。一个BFC区域宝含创建该上下文的所有子元素,但是不包括创建了显得BFC区域的子元素。
创建了BFC的元素,它内部的元素不送外部元素影响,也不会影响外部元素,是一个独立的区域。
2、创建BFC区域
-
body根元素
-
设置浮动,但是不能是none,
-
设置绝对定位absoulte或者固定定位 fixed
-
设置overflow属性,但是不能为visible
-
行内快的显示模式 diaplay:inline-block
3、解决的问题
1、清除浮动
当以某个元素成为BFC时,如果他里面包含浮动元素时,会计算浮动元素的高度
.father{
width: 100%;
background-color: red;
}
.son{
width: 100px;
height: 100px;
float: left;
background-color: green;
}
</style>
</head>
<body>
<div class="father">
1111111111111111111
<div class="son"></div>
</div>
</body>
上面的代码会出现下面的效果,父盒子的高度是自己本身的高度,并没有包含浮动元素的高度。
下面我们将父盒子变为一个BFC区域
.father{
width: 100%;
height: 50px;
background-color: red;
overflow: hidden;
}
.son{
width: 100px;
height: 100px;
float: left;
background-color: green;
}
可以看出浮动元素的高度也别计算到了父级元素的高度中
2、解决垂直外边距合并问题
在同一个BFC区域下的元素会进行垂直方向的外边距合并
当垂直方向的两个元素都设有外边胡时,会进行外边距的合并
<style>
.father{
width: 100px;
height: 100px;
background-color: red;
margin-bottom: 30px;
}
.son{
width: 100px;
height: 100px;
background-color: green;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="father">
</div>
<div class="son"></div>
</body>
为了解决这个问题我们可以给两个div外面都讨一个div,并让这个div成为BFC区域,即让两个元素处于不同的BFC区域中
<style>
.box{
overflow: hidden;
}
.father{
width: 100px;
height: 100px;
background-color: red;
margin-bottom: 30px;
}
.son{
width: 100px;
height: 100px;
background-color: green;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="box">
<div class="father">
</div>
</div>
<div class="box">
<div class="son"></div>
</div>
</body>
3、解决包含塌陷问题
有时候当我们给子元素设置margin-top时,父盒子会跟着子盒子跑
.father {
width: 200px;
height: 200px;
background-color: red;
}
.son {
width: 100px;
height: 100px;
background-color: green;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
这个时候我们就可以将父盒子变为一个BFC区域来解决该问题
.father {
width: 200px;
height: 200px;
background-color: red;
overflow: hidden;
}
总结来说: 一个BFC区域只包含其子元素,不包括其子元素的子元素。并不是所有的元素都能成为一块BFC区域,只有当这个元素满足条件的时候才会成为一块BFC区域。不同的BFC区域之间是相互独立的,互不影响的。利用这个特性我们可以让不同BFC区域之间的布局不产生影响