fixed定位 zindex=100,absolute定位 zindex=20,absolute定位的元素在fixed定位的元素上面
现象说明 fixedzindex > absolutezindex
.leftChild
{
position
: absolute
;
left
: 0;
top
: 0;
z
-index
: 20;
}
.rightChild
{
position
: fixed
;
left
: 0;
top
: 0;
z
-index
: 100;
}
效果图:leftChild元素位于rightChild元素上方,尽管rightChild 的zindex更大
代码结构分析
html结构
<div
class="main">
<div
class="top">
<div
class="left">
<div
class="leftParent parent">
parentA
<div
class="leftChild child">
leftChild
</div
>
</div
>
</div
>
<div
class="right">
<div
class="rightParent parent">
parentB
<div
class="rightChild child">
rightChild
</div
>
</div
>
</div
>
</div
>
</div
>
style
.top
{
height
: 100%;
padding
-right
: 500px
;
position
: relative
;
}
.left
{
width
: 100%;
height
: 100%;
position
: absolute
;
left
: 0;
top
: 0;
z
-index
: 2;
}
.right
{
width
: 500px
;
height
: 100%;
background
-color
: yellow
;
position
: absolute
;
right
: 0;
top
: 0;
z
-index
: 1;
}
.parent
{
position
: relative
;
width
: 100%;
height
: 300px
;
}
.child
{
width
: 200px
;
height
: 200px
;
}
.leftChild
{
position
: absolute
;
left
: 0;
top
: 0;
z
-index
: 20;
background
-color
: papayawhip
;
}
.rightChild
{
position
: fixed
;
left
: 80px
;
top
: 20px
;
z
-index
: 100;
background
-color
: pink
;
text
-align
: right
;
}
细心的同学会发现
left元素和right元素是兄弟元素left元素的zindex比right元素的zindex值更大 那么造成这个种现象的原因是什么呢?我们来看MDN是怎么说的 fixed属性会创建新的层叠上下文,当元素祖先的transform,perspective活filter属性非none时,容器由视口改为该祖先。 结合案例可以看出: 1、rightChild的父元素position设为relative,所以此时zindex相对的容器视口为rightParent 2、rightParent的父元素是right 3、right元素绝对定位zindex为1,而left元素zindex为2,所以在parentRight元素中的任何子元素,只要设置的position=fixed,定位的元素zindex设置的再大,也会被leftChild 覆盖 解决方式: 设置left元素的zindex大于right元素的zindex
.left {
width: 100%
;
height: 100%
;
position: absolute
;
left: 0
;
top: 0
;
z-index: 1
;
}
.right {
width: 500px
;
height: 100%
;
background-color: yellow
;
position: absolute
;
right: 0
;
top: 0
;
z-index: 1
;
}
PS:z-index相同的情况下,后面一个元素的层级更高
刷新页面效果图如下: 同学是否有遇到类似的问题呢?欢迎留言讨论