一、BFC的定义
BFC(Block Formating Content) ,即为块级格式化上下文,是CSS规范中提出的提个概念定义的是页面中一块渲染区域。同一个格式化上下文(渲染区域)和不和格式化上下文(渲染区域)的定位方式会发生改变
二、BFC解决父元素塌陷
父元素塌陷的基本描述:
-在文档流中,如果没有设置宽高,则值为:auto(和父元素或浏览器宽度相同)
- 在文档流中如果没有设置父元素高度,则高度由“内容”(子元素)撑开
- 当子元素设置浮动,子元素会脱离文档流,此时子元素无法撑开父元素,导致父元素高度塌陷。
- 如果父元素高度塌陷,则父元素下的兄弟元素会上移,导致页面布局混乱
//C3部分代码
<style>
.outer {
border: 2px solid red;
/* 开启父元素BFC */
overflow: hidden;
}
.inner {
width: 200px;
height: 200px;
background-color: yellow;
float: left;
}
</style>
//h5代码
<div class="outer">
<div class="inner"></div>
</div>
三、BFC解决外边距传递
外边距传递的基本描述
-在对子元素设置外边距时,子元素没有以父元素为标准以父元素为标准移动,而是将外边距传递给父元素,父元素发生了 移动。此时,我们可以开启BFC来消除外边距传递。
//c3部分代码
<style>
.outer {
width: 200px;
height: 200px;
background-color: red;
/* 父元素开启BFC */
overflow: hidden;
}
.inner {
width: 100px;
height: 100px;
background-color: yellow;
margin-top: 100px;
}
</style>
//h5部分代码
<div class="outer">
<div class="inner"></div>
</div>
四、外边距重叠
//c3部分代码
<style>
.box1 {
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 100px;
}
.box2 {
width: 200px;
height: 200px;
background-color: yellow;
margin-top: 100px;
}
/* 开启BFC */
.outer {
overflow: hidden;
}
</style>
//h5部分代码
<div class="box1"></div>
<div class="outer">
<div class="box2"></div>
</div>
五、元素覆盖
//c3部分代码
<style>
.box1 {
width: 200px;
height: 200px;
background-color: red;
float: left;
}
.box2 {
width: 200px;
height: 200px;
background-color: yellow;
/* 开启BFC */
overflow: hidden;
}
/* .box3 {
width: 200px;
height: 200px;
background-color: #666;
} */
</style>
//h5部分代码
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>