当元素在某一位置重叠时,部分元素显示的优先级较高,部分元素显示的优先级较低。这些元素在网页上堆叠形成三维结构,指向用户的就是z轴。网页上可能重叠的元素,在显示上具有一定顺序。
网页可能重叠的元素的优先级
- 背景background
- 边框border
- 常规流块级元素
- 浮动元素float
- 块级元素block
- 行级(内联)元素inline
- z-index为默认值
- 定位元素z-index为0
- z-index为正数(越高显示优先级越高)
效果展示
源代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: rgba(0,0,0,0.5);
border:10px solid #0cc;
width:1200px;
height:500px;
margin:0px;
padding:0px;
}
.float{
width:100px;
height:100px;
margin-top:-80px;
margin-left: 40px;
background-color: #ccc;
float: left;
}
.block{
width:100px;
height:100px;
margin-top:20px;
margin-left:10px;
background-color: red;
}
span{
margin-left: -20px;
background-color: pink;
}
.z_lower_0{
position: absolute;
top:10px;
left:10px;
z-index: -1;
width:100px;
height:100px;
background-color: green;
}
.z-greater_than0{
width:100px;
height:100px;
background-color: brown;
position: absolute;
left:160px;
top:120px;
}
.z_0{
width:100px;
height:100px;
background-color: #ccc;
position: absolute;
left:180px;
top:140px;
z-index: 0;
}
.z_more_0{
width:100px;
height:100px;
background-color: pink;
position: absolute;
top:160px;
left:200px;
z-index: 1;
}
</style>
</head>
<body>
<div class="block">块级</div>
<div class="float">浮动</div>
<span>行内--------------</span>
<div class="z_lower_0">z-index为负值</div>
<div class="z-greater_than0">z-index为默认值</div>
<div class="z_0">z-index=0</div>
<div class="z_more_0">z-index>0</div>
</body>
</html>
以下引用MDN文档内容,个人感觉重要性不大,理解即可。
创建堆叠上下文的元素
- 文档根元素<html>
- position 值为 absolute(绝对定位)或 relative(相对定位)且 z-index 值不为 auto 的元素
- position 值为 fixed(固定定位)或 sticky(粘滞定位)的元素(沾滞定位适配所有移动设备上的浏览器,但老的桌面浏览器不支持)
- flex (flex) 容器的子元素,且 z-index 值不为 auto;
- grid (grid) 容器的子元素,且 z-index 值不为 auto;
- opacity 属性值小于 1 的元素(参见 the specification for opacity);
- mix-blend-mode 属性值不为 normal 的元素;
- 以下任意属性值不为 none 的元素:
- transform filter backdrop-filter perspective clip-path mask / mask-image / mask-border
- isolation 属性值为 isolate 的元素
- will-change 值设定了任一属性而该属性在 non-initial 值时会创建层叠上下文的元素(参考这篇文章);
- contain 属性值为 layout、paint 或包含它们其中之一的合成值(比如 contain: strict、contain: content)的元素。
在层叠上下文中,子元素同样也按照上面解释的规则进行层叠。 重要的是,其子级层叠上下文的 z-index 值只在父级中才有意义。子级层叠上下文被自动视为父级层叠上下文的一个独立单元。
本文参考MDN关于层叠(堆叠)上下文文档
笔者尚在学习中,如有不足或错误,欢迎指正。