Why “z-index” does not work for element having transform: translateY()

杀马特。学长 韩版系。学妹 提交于 2019-12-10 12:46:43

问题


Below is the snippet:

.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>

As can be seen, the .up element has higher z-index than .down element. However, the .down element still locates in front of the .up element somehow..

Does anyone have ideas about this? How to fix this?


回答1:


  1. For z-index to work position must be applied as absolute, relative or fixed. Add position: relative; to the .down element
  2. As there is no parent-child hierarchy, negative z-index should be applied to make the element go behind.

Demo

.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>



回答2:


Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Add position:relative to .up class

.up {
  background-color: red;
  height: 100px;
  z-index: 100;
  position: relative;
  opacity: .5;
}
.down {
  background-color: yellow;
  height: 100px;
  width: 50%;
  margin: 0 auto;
  transform: translateY(-50%);
}
<div class="up"></div>
<div class="down"></div>



回答3:


Just keep in mind that elements with non-static positioning will always appear on top of elements with default static positioning.

While you are dealing with two elements , you can use the values 0, 1 or -1. Dont complicate yourself with higher values.



来源:https://stackoverflow.com/questions/32816750/why-z-index-does-not-work-for-element-having-transform-translatey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!