BFC的基本概念
块级格式化上下文
BFC布局规则=>BFC的原理(渲染原理)
1.内部的Box会在垂直方向上一个接一个放置
2.Box垂直方向的距离由margin决定,属于同一个BFC的两个相邻的Box的margin会发生重叠。
3.每个元素的margin box的左边,与包含块border box的左边相接触
4.BFC的区域不会与float box重叠
5.BFC是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素
6.计算BFC的高度时,浮动元素也会参与计算
怎么创建BFC
- float的值不为none
- overflow的值不为visibled(hideen scroll auto inherit)
- display的值为inline-block,table-cell,table-caption,flex,inline-flex
- position的值为absolute或者fixed
BFC的使用场景
1.防止margin重叠(塌陷)
两个相邻的box垂直方向margin重叠
<body>
<style>
p {
color: #f55;
background: #fcc;
width: 200px;
line-height: 200px;
text-align: center;
margin: 100px;
}
</style>
<p>温清夜</p>
<p>温清夜</p>
</body>
有规则2知道,属于同一个BFC的相邻两个margin会发生重叠,我们只需要在一个p外面包裹一个BFC容器,就可以!
<style>
p {
color: #f55;
background: #fcc;
width: 200px;
line-height: 200px;
text-align: center;
margin: 100px;
}
.warper {
overflow: hidden;
}
</style>
<div class="warper">
<p>温清夜</p>
</div>
<p>温清夜</p>
2 两栏布局,左边固定,右边自适应
<style>
.left {
width: 200px;
height: 100px;
background: red;
float: left;
}
.right {
height: 110px;
background: yellow;
}
</style>
<div class="left"></div>
<div class="right"></div>
通过上图你会发现,右边的布局内容和左边的浮动部分重叠在了一起!根据规则可知,BFC容器和浮动元素不必发生重叠,所以我们可以在右边的元素中设置BFC
<style>
.left {
width: 200px;
height: 100px;
background: red;
float: left;
}
.right {
height: 110px;
background: yellow;
overflow: hidden;
}
</style>
<div class="left"></div>
<div class="right"></div>
3 BFC清除浮动
<style>
.parent {
border: 1px solid black;
}
.child {
width: 100px;
height: 100px;
background: yellow;
float: left;
}
</style>
<div class="parent">
<div class="child"></div>
</div>
计算BFC的高度时,浮动元素也会参与计算,设置父元素为BFC
<style>
.parent {
border: 1px solid black;
overflow: hidden;
}
.child {
width: 100px;
height: 100px;
background: yellow;
float: left;
}
</style>
<div class="parent">
<div class="child"></div>
</div>