浅谈BFC

BFC是什么?
首先说一下BFC是什么,概念从哪里来?BFC全称叫做(Block Formatting Context)中文叫块级格式化上下文,是一个网页的概念。网页是一个一个盒子组成的,那么这个BFC到底有什么用途呢?看下面具体分析。

怎么触发BFC
浮动元素:float 除 none 以外的值。
绝对定位元素:position (absolute、fixed)。
display 为 inline-block、table-cells、flex。
overflow 除了 visible 以外的值 (hidden、auto、scroll)。
遇到哪些问题需要用到BFC
在网页制作过程中由于浏览器加载是自上而下的原因(也可能是其他原因,个人是这么理解),外边距上下会取最大值,左右不影响,所以会导致以下局面。

html
<div class="demo1"></div>
<div class="demo2"></div>
css
.demo1{width: 200px;height: 200px;background-color: red;margin-bottom: 20px;}
.demo2{width: 200px;height: 200px;background-color: black;margin-top: 30px;}
外边距重叠


浏览器解析的时候会使外边距叠加在一起,这时候就是遇到了BFC的问题,那么就要通过触发BFC来解决这个问题。

html
<div class="demo1"></div>
<div class="box">
<div class="demo2"></div>
</div>
css
.box{position :absolute;}
.demo1{width: 200px;height: 200px;background-color: red;margin-bottom: 20px;}
.demo2{width: 200px;height: 200px;background-color: black;margin-top: 30px;}
BFC
给其中一个子元素讨一个DIV,通过给这个DIV设置属性触发BFC就可以解决问题。


高度塌陷
在举一个例子理解BFC。

html
<div class="box">
<div class="demo"></div>
</div>
css
.box{width: 300px;height: 300px;background-color: black;}
.demo{width: 100px;height: 100px;background-color: red;margin: 20px;}
BFC


这个时候红色DIV左右外边距并没有重叠 但是上外边距和父级重叠在了一起,这时候就要触发BFC来解决这个问题。

html
<div class="box">
<div class="demo"></div>
</div>
css
.box{width: 300px;height: 300px;background-color: black;overflow: hidden;}
.demo{width: 100px;height: 100px;background-color: red;margin: 20px;}
BFC

原文链接:https://blog.csdn.net/return_js/article/details/81266131

posted @ 2019-10-10 09:30  前端海  阅读(424)  评论(0编辑  收藏  举报