BFC(block formatting context)块级格式化上下文,是Web页面盒模型布局的CSS渲染模式,是一个独立的渲染区域或者可以认为是一个独立容器。该容器中的子元素不会影响容器外的元素,反之外部元素也不会影响容器内的元素。其中包括浮动和外边距(margin)合并等。BFC特性能杜绝布局中的意外情况发生。
形成BFC的条件
1.浮动元素:float属性值除none以外的元素。
2.定位元素:position属性值为( absolute 或是 fixed )的元素。
3.dispaly属性值为(inline-block、table-cell、table-caption、flex、inline-flex)其中任意一个值的元素。
4.overflow属性值除visible以外的元素。(hidden、auto、scroll).。
BFC的特性
1.内部盒子会在垂直方向上一个接一个的放置。
2.垂直方向上的距离由margin决定,属于同一个BFC盒子的margin会重叠。
3.在BFC盒子中,每个盒子的左边缘会触碰父容器的左边缘,即在没有margin和padding值时,父border内边与子border外边
重叠。
4.BFC盒子不会与浮动盒子产生交集,而是紧贴浮动元素边缘。
5.如果父容器没有设置高度,但子盒子中存在浮动元素,那么在计算bfc的高度时,会计算上浮动盒子的高度。
6.BFC是一个独立的容器,容器内的元素不会影响外部元素,同样外部元素也不会影响容器内元素。
BFC实例
(1)BFC中的盒子对齐
特性的第一条是:内部的Box会在垂直方向上一个接一个的放置。
浮动的元素也是这样,box3浮动,他依然接着上一个盒子垂直排列。并且所有的盒子都左对齐。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>BFC中的盒子对齐</title>
</head>
<body>
<div class="content">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
</div>
</body>
</html>
css:
div{
height: 20px;
}
.content{
position:absolute; /* 创建一个BFC环境 */
background:#eee;
height:auto;
}
.box1{
width:400px;
background-color:red;
}
.box2{
width:300px;
background-color:blue;
}
.box3{
width:100px;
background-color:green;
float:left; /* box3为浮动元素 */
}
.box4{
width:200px;
background-color:yellow;
height:40px;
}
(2)外边距折叠
特性的第二条:垂直方向上的距离由margin决定
在常规文档流中,两个兄弟盒子之间的垂直距离是由他们的外边距所决定的,但不是他们的两个外边距之和,而是以较大的为准。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>外边距折叠</title>
<style>
.container {
overflow: hidden;
width: 500px;
height: 500px;
background-color: red;
}
.wrapping{
overflow:hidden;
}
.box1 {
height: 100px;
margin: 50px 0;
background-color: green;
}
.box2 {
height: 100px;
margin: 100px 0;
background-color: green;
}
</style>
</head>
<body>
<p>1.常规文件流中,兄弟盒子之间的垂直距离用margin决定,且取最大值而不是求和</p>
<div class="container">
<div class="box1"></div>
<div class="box2"></div>
</div>
<p>2.额外增加一个BCF</p>
<div class="container">
<div class="wrapping">
<div class="box1"></div>
</div>
<div class="box2"></div>
</div>
</body>
</html>
(3)不被浮动元素覆盖
以常见的两栏布局为例。
左边固定宽度,右边不设宽,因此右边的宽度自适应,随浏览器窗口大小的变化而变化。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>不被浮动元素覆盖</title>
<style>
.column:nth-of-type(1) {
float: left;
width: 200px;
height: 100px;
margin-right: 10px;
background-color: red;
}
.column:nth-of-type(2) {
overflow: hidden;/*创建bfc */
height: 300px;
background-color: purple;
}
</style>
</head>
<body>
<div class="column"></div>
<div class="column"></div>
</body>
</html>