Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 952
Hanfei Sun Avatar asked Sep 28 '15 06:09

Hanfei Sun


3 Answers

  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>
like image 56
Tushar Avatar answered Oct 09 '22 15:10

Tushar


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>
like image 3
akash Avatar answered Oct 09 '22 17:10

akash


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.

like image 1
VISHAL VM Avatar answered Oct 09 '22 17:10

VISHAL VM