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?
z-index
to work position
must be applied as absolute
, relative
or fixed
. Add position: relative;
to the .down
elementz-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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With