BFC,块格式化上下文(Block Formatting Context)。W3C CSS2.1中的一个概念。
FC:它是一块渲染区域,遵守相应的渲染规则,这些规则决定了:
内部元素的定位方式
与外部元素的位置关系
BFC的布局渲染规则:
内部的Box会在垂直方向,一个接一个地放置。
Box垂直方向的距离由margin决定。属于同一个BFC的两个相邻Box的margin会发生重叠
每个元素的margin box的左边,与包含块border box的左边相接触。即使存在浮动也是如此。
BFC的区域不会与float box重叠。
BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素。反之也是如此。
计算BFC的高度时,浮动元素也参与计算。
如何触发BFC:
html根元素
float值不是none的元素
overflow不是visible的元素
display值为inline-block,table-cell,table-caption的元素
position值为absolute,fixed元素
BFC的四个代码实验:
自适应的两栏布局
=====================举例============================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div {
height: 800px;
}
.left {
width: 300px;
background-color: #f00;
float: left;
margin-right: 10px;
}
/* 通过把.right变成BFC来使得其不与float重合 */
.right {
background-color: #000;
/* 变成BFC的其中一个方法 */
overflow: hidden;
}
</style>
</head>
<body>
<div class="left"></div>
<div class="right"></div>
</body>
</html>
=====================效果============================
阻止元素被浮动元素覆盖
=====================举例============================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.left {
width: 300px;
height: 800px;
background-color: #f00;
float: left;
margin-right: 10px;
}
/* 通过把.right变成BFC来使得其不与float重合 */
.right {
height: 800px;
background-color: #000;
/* 变成BFC的其中一个方法 */
overflow: hidden;
}
.mid {
width: 100px;
height: 100px;
background-color: #0f0;
overflow: hidden;
/* 或者变成float:left也可以 */
}
</style>
</head>
<body>
<div>
<div class="left"></div>
</div>
<div>
<div class="mid"></div>
<div class="right"></div>
</div>
</body>
</html>
清除内部的浮动(无例子)
分属于不同BFC的box,margin不会合并
=====================举例============================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div1,
#div2{
width: 200px;
height: 200px;
}
#div1 {
background-color: #f00;
margin-bottom: 100px;
}
#div2 {
background-color: #000;
margin-top: 50px;
}
.div2-wrap {
overflow: hidden;
}
</style>
</head>
<body>
<div id="div1"></div>
<div class="div2-wrap">
<div id="div2"></div>
</div>
</body>
</html>
=====================效果============================
什么是BFC?
原文:https://www.cnblogs.com/Friday1/p/14698691.html