这是我参与「第四届青训营 」笔记创作活动的的第1天
昨天的青训营,让我影响最深刻的就是关于BFC,IFC,FFC,GFC,我完全不知道FC是什么,于是就去查阅了各种资料,于是就有了本文
一.关于文档流
文档流分为 定位流、浮动流 和 常规流 三种。
- 根元素、浮动和绝对定位的元素会脱离常规流
- 其它元素都在常规流之内(in-flow)
- 常规流中的盒子,在某种格式化上下文(即FC)中参与布局
二.关于FC的概念
FC 即Formatting context (格式化上下文),是W3C CSS2.1规范中的一个概念。它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系、相互作用。
目前主要的css格式化上下文主要包括四种类型:
- Block fomatting context (块级格式化上下文,简称BFC)
- Inline formatting context (内联级格式上下文,简称IFC)
- Flexible Formatting Contex(弹性盒格式化上下文,简称FFC,css3新增)
- Grids Formatting Context(网格格式化上下文,简称GFC,css3新增)。
三.BFC,块级格式化上下文
(1)BFC 布局排版规则
- BFC 内盒子从上到下摆放
- 每个元素的左外边距与包含块的左边界相接触(从左向右),即使浮动元素也是如此。(这说明 BFC 中子元素不会超出他的包含块,而
position为absolute的元素可以超出他的包含块边界) - BFC 内盒子的垂直 margin 合并
- BFC 内盒子的 margin 不会与外面的合并
- BFC 不会和浮动元素重叠
- 计算BFC的高度时,浮动元素也参与计算
(2)BFC的创建条件
- 根元素
- 浮动、绝对定位、inline-block
- Flex子项和Grid子项
- overflow 值不是 visible 的块盒
- display: flow-root;
(3)BFC的应用场景
1.解决margin collapse(外边距折叠)
<style>
.a {
background: lightblue;
height: 100px;
margin-bottom: 100px;
}
.b {
background: coral;
height: 100px;
margin-top: 120px;
}
</style>
<body>
<div class="a"></div>
<div class="b"></div>
</body>
</html>
问题原因:这种情况产生的根本原理就是两个相邻的元素均处于同一个 BFC,触发了BFC 内的排版规则,即
垂直 margin 合并
尽管两个div分别设置了margin-bottom与margin-top,但还是以最大的margin为准,即两个div之间的距离为120px
解决方式:于是我们可以在b容器外创建一个c容器, 并设置c容器的overflow为hidden,就可以触发该容器生成一个新BFC,那么a和b便不属于一个BFC,于是垂直的margin便不会合并了
<style>
.a {
background: lightblue;
height: 100px;
margin-bottom: 100px;
}
.b {
background: coral;
height: 100px;
margin-top: 120px;
}
.c {
overflow: hidden;
}
</style>
<body>
<div class="a"></div>
<div class="c">
<div class="b"></div>
</div>
</body>
2.清除浮动
<style>
.parent {
width: 300px;
border: 5px solid #eee;
}
.child {
width: 200px;
height: 200px;
background-color: orange;
float: left;
}
</style>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
根据BFC布局排版规则
计算BFC的高度时,浮动元素也参与计算
所以,此时我们可以给parent添加一个overflow: hidden触发该容器生成一个新BFC.那么parent在计算高度时,parent内部的浮动元素child也会参与计算。
.parent {
width: 300px;
border: 5px solid #eee;
overflow: hidden
}
所以,简单来说,也可以理解为
BFC内部子元素再怎么翻江倒海,翻云覆雨都不会影响外部的元素
3.自适应布局
<style>
.a {
width: 200px;
height: 200px;
background-color: orange;
float: left;
}
.b {
height: 300px;
background-color: skyblue;
}
</style>
<body>
<div class="a"></div>
<div class="b"></div>
</body>
根据BFC布局排版规则
BFC 不会和浮动元素重叠
我们可以通过为b容器添加一个overflow: hidden触发该容器生成一个新BFC.从而实现自适应布局
.b {
height: 300px;
background-color: skyblue;
overflow: hidden;
}
四.结语
不过话说回来, 其实现在基本使用的都是FFC 和 GFC了 ( ̄︶ ̄)
如果文章对你有帮助的话,欢迎点个赞( ̄﹃ ̄),如果有不对的,欢迎评论区指出