下面是片段:
.up {
background-color: red;
height: 100px;
z-index: 100;
}
.down {
background-color: yellow;
height: 100px;
width: 50%;
margin: 0 auto;
z-index: 1;
transform: translateY(-50%);
}
<div class="up"></div>
<div class="down"></div>
可以看出,.up
元素的 z-index
高于 .down
元素。但是,.down
元素仍然以某种方式位于 .up
元素的前面。
有人对此有想法吗?如何解决这个问题?
最佳答案
- 要使
z-index
起作用,position
必须应用为absolute
、relative
或fixed
。在.down
元素中添加position: relative;
- 由于没有父子层次结构,因此应应用负
z-index
以使元素落后。
演示
.up {
background-color: red;
opacity: .5; /* For DEMO Purpose */
height: 100px;
/* z-index: 100; /* Not required. Not work #1 */
}
.down {
background-color: yellow;
height: 100px;
width: 50%;
margin: 0 auto;
z-index: -1; /* Update this */
transform: translateY(-50%);
position: relative; /* Add this */
}
<div class="up"></div>
<div class="down"></div>
关于html - 为什么 "z-index"不适用于具有转换 : translateY() 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816750/