层叠上下文:
层叠上下文:Stacking Context。是 CSS 中用于控制元素在 z 轴上的堆叠顺序的机制。
z 轴:垂直于屏幕的轴。
层叠上下文的特点:
-
层叠上下文可以嵌套。例如有一个元素是层叠上下文元素,那么在它内部还可以继续嵌套层叠上下文元素。
-
层叠上下文元素之间相互独立。例如两个元素都是层叠上下文元素,那么它们的子元素的排列规则相互之间是没有关系的。
<template> <!-- 因为 box2 的层级要比 box1 高,因此即使 box1 中的子元素层级再高,也比不过 box2 中的子元素 --> <div class="box1"> <div class="box11"></div> </div> <div class="box2"> <div class="box22"></div> </div> </template> <script setup> </script> <style scoped> .box1 { width: 200px; height: 200px; background-color: red; position: absolute; z-index: 1; } .box11 { width: 100px; height: 100px; background-color: yellow; position: absolute; z-index: 999; } .box2 { width: 60px; height: 60px; background-color: blue; position: absolute; z-index: 100; } .box22 { width: 30px; height: 30px; background-color: green; position: absolute; z-index: 1; } </style>
-
即使层叠上下文元素没有设置
z-index
,它也要比普通元素的级别高。因为它的默认层叠等级为z-index:0
创建层叠上下文的方式:
- HTML 中的根元素本身就具有层叠上下文,称为根层叠上下文。
- 传统层叠上下文:
- position 属性为 relative 或者 absolute,且
z-index
为具体数值。 - position 属性为 fixed 或者 sticky。
这里的传统主要是指 CSS3 之前创建层叠上下文元素的方式。
- position 属性为 relative 或者 absolute,且
- CSS3 中的很多新属性也可以产生层叠上下文,常见的有:
- display 属性为 flex 或者
inline-flex
,且z-index
为具体数值。 - display 属性为 grid 或者
inline-grid
,且z-index
为具体数值。 - opacity 属性值小于 1。
- transform、filter 等属性。
- display 属性为 flex 或者
层叠顺序:
层叠顺序:在同一个层叠上下文中,元素按照特定规则堆叠的顺序。z-index>0 元素
> z-index:auto 元素或者 z-index:0 元素
> inline 元素或者 inline-block 元素
> float 元素
> block 元素
> z-index<0 元素
> background 元素的背景或者 border 元素的边框
。
<template>
<div class="container">
<!-- 在同一个层叠上下文中,浮动元素会在 z-index 为负数的上面 -->
<div class="box1"></div>
<div class="box2"></div>
</div>
</template>
<script setup>
</script>
<style scoped>
.container {
width: 100px;
height: 100px;
background-color: red;
position: relative;
z-index: 0;
}
.box1 {
width: 60px;
height: 60px;
background-color: blue;
position: absolute;
z-index: -1;
}
.box2 {
width: 30px;
height: 30px;
background-color: green;
float: left;
}
</style>