什么是堆叠上下文
MDN 解释:
层叠上下文是HTML元素的三维概念,这些HTML元素在一条假想的相对于面向(电脑屏幕的)视窗或者网页的用户的z轴上延伸,HTML元素依据其自身属性按照优先级顺序占用层叠上下文的空间。
形成堆叠上下文的条件:
- 根元素 (HTML)。
z-index
值不为auto
的 绝对/相对定位元素。- 固定(fixed) / 沾滞(sticky)定位(沾滞定位适配所有移动设备上的浏览器,但老的桌面浏览器不支持)。
z-index
值不为auto
的 flex 子项 (flex item),即:父元素 display: flex|inline-flex。z-index
值不为auto
的grid子项,即:父元素display:grid。opacity
属性值小于 1 的元素。transform
属性值不为none
的元素。mix-blend-mode
属性值不为normal
的元素。transform
属性值不为none
的元素 。filter
值不为none
的元素。perspective
值不为none
的元素。clip-path
值不为none
的元素。mask
/mask-image
/mask-border
不为none
的元素。isolation
属性被设置为isolate
的元素。- 在
will-change
中指定了任意CSS属性。-webkit-overflow-scrolling
属性被设置touch
的元素。contain
属性值为layout
,paint
,或者综合值比如strict
,content
。
层叠准测
引用张鑫旭
- 谁大谁上:当具有明显的层叠水平标示的时候,如识别的z-indx值,在同一个层叠上下文领域,层叠水平值大的那一个覆盖小的那一个。通俗讲就是官大的压死官小的。
- 后来居上:当元素的层叠水平一致、层叠顺序相同的时候,在DOM流中处于后面的元素会覆盖前面的元素。
<style>
div {
height: 100px;
}
.one {
background: gray;
position: relative;
z-index: 2;
}
.two {
background: yellow;
z-index: 1;
position: relative;
margin-top: -60px;
}
</style>
<body>
<div class='one'>one</div>
<div class='two'>two</div>
</body>
谁大谁上
<style>
div {
height: 100px;
}
.one {
background: gray;
}
.two {
background: yellow;
margin-top: -60px;
}
</style>
<body>
<div class='one'>one</div>
<div class='two'>two</div>
</body>
后来居上
堆叠顺序
堆叠顺序就是在同一个堆叠上下文中,当元素发生层叠时规定元素的垂直显示顺序。
<style>
.main {
width: 200px;
height: 200px;
border: 10px solid rgba(255, 0, 0, 0.3);
background: yellow;
}
.block {
background: pink;
height: 25px;
color: red;
}
.float {
background: green;
height: 25px;
width: 100px;
margin-top: -15px;
color: blue;
float: left;
}
</style>
<body>
<div class='main'>
<div class='block'>块级元素</div>
<div class='float'>浮动元素</div>
</div>
border
的层级是高于 background
,但都小于块级元素、浮动元素、行内元素。
浮动元素的层级是高于块级元素,但是行内元素比两者都高。
<style>
.main {
width: 200px;
height: 200px;
background: rgba(255, 0, 0, 0.5);
color: rgb(255, 255, 255);
}
.position {
background: green;
position: relative;
margin-top: -5px;
}
.position1 {
background: blue;
height: 70px;
position: relative;
z-index: -1;
}
</style>
<body>
<div class='main'>
行内元素
<div class='position'>定位元素</div>
<div class='position1'>定位元素(z-index : -1)</div>
</div>
</body>
定位元素且 z-index:auto
的层级大于行内元素。
具有堆叠上下文的元素且 z-index
为负数,则层次小于背景之后。
<style>
.main {
width: 200px;
height: 200px;
background: pink;
}
.position {
background: green;
position: relative;
z-index:auto;
}
.position1 {
background: yellow;
height: 70px;
position: relative;
z-index: 1;
margin-top: -5px;
}
</style>
<body>
<div class='main'>
<div class='position'>定位元素</div>
<div class='position1'>定位元素(z-index 正数)</div>
</div>
</body>
具有堆叠上下文的元素且 z-index 为正数的层级大于定位元素且 z-index:auto
。
参考:
[1] 深入理解CSS中的层叠上下文和层叠顺序
[2] css层叠顺序探究