把这两个放在一篇文章里是因为这两个东西都叫上下文,那咱就一锅炖了_!
BFC - block formatting context
个人理解:独立容器
形成条件
- 根元素
- display:flex、inline-block、table-cell
- position:absolute、fixed
- float 不为 none
- overflow 不为 visible
特性
先说下个人的理解吧:BFC 其实就是一个密闭的空间,不受其它元素影响,也不会影响其它元素
- BFC 内普通元素是垂直排列的,上下 margin 会发生重叠,与 BFC 的 border 相接触
- BFC 会计算浮动元素的高度
- BFC 不会与浮动元素发生重叠
- BFC 是独立容器,不会与外界产生反应
作用
- 如果 margin 发生了重叠,可以利用特性 4,将发生重叠的元素放到不同的 BFC 中即可避免 margin 重叠问题
- 发生了高度塌陷,将父元素变为 BFC 即可
- 利用特性 3 可以实现两三栏布局
<!-- css -->
<style>
.left {
float: left;
width: 100px;
height: 100%;
background-color: yellow;
}
.right {
float: right;
width: 100px;
height: 100%;
background-color: red;
}
.center {
height: 100%;
background-color: green;
overflow: hidden;
}
</style>
<!-- dom结构 center在最后 -->
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
可以和三栏常见布局圣杯、双飞翼、flex作对比,虽然我现在基本都是用 flex
SC - stacking context
个人理解:控制 z 轴上元素的显示顺序
形成条件
- 根元素
- position 不为 static,并且设置了
z-index 为数值
的元素 - 一些 css3 中的新属性
第三点包括:
- z-index 不为 auto 的 flex 项(flex 子元素)
- opacity 不为 1
- transform 不为 none
- filter 不为 none
- -webkit-overflow-scrolling 为 touch 等等
- mix-blend-mode 不为 normal
- isolation 为 isolate
- will-change
层叠等级
其实我也不知道为啥非要整出这么多概念…决定了同一个层叠上下文中
元素在 z 轴上的显示顺序。
常见会产生层叠上下文的情况:
- 根元素html
- position不为static, 并且设置z-index
- display为flex,子元素z-index不为auto,子元素为层叠上下文
- opatic不为1
- transform不为none
这里的重中之中就是同一层叠上下文中比较才有意义