0

**Here is a simple code **

div {
  border: 1px solid blue;
}

.one {
  background-color: red;
  width: 300px;
  height: 300px;
  
}


.two {
  background-color: orange;
  width: 300px;
  height: 300px;
  
  position: relative;
  top: 100px;
  left: 100px;
  
  z-index: 10;
}

.twenty {
  
  background-color: pink;
  width: 300px;
  height: 300px;  
  position: relative;
  top: 100px;
  left: 100px;
  z-index: 500;
}


.three {
  margin-top: -10px;
  margin-left: 10px;
  background-color: yellow;
  width: 300px;
  height: 300px;
}


.four {
  background-color: green;
  width: 300px;
  height: 300px;
  
  position: relative;
  top: 80px;
  left: 120px;
  z-index: 11;
}
<div class="one">

  <div class="two">

    <div class="twenty">
        Can pink be above green?
    </div>
  </div>
</div>
<div class="three">
  <div class="four">

  </div>
</div>

How to make the pink square to be above the green square? Is it possible with CSS changes only without HTML changes? Why z-index applied to the .twenty class doesn't work in this case? Thank you.

This question is NOT a duplicate of Why can't an element with a z-index value cover its child? :

In this question we'd like the child to cover, not the parent!

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

3 Answers3

2

All layers, except the twentieth, should not have Z order. We specify absolute an order and an order of a layer on Z.

.twenty{
position: absolute;
...
z-index: 1;
}
1

You should set .four with a lower z-index than .two which is the element that contains .twenty but this may not be the expected result (green also becomes under the orange).

It's not possible without changing the HTML structure, like putting .twenty inside .four, or redefining all the indexes. This is how the stacking context works.

Given this code:

<div class="A">
  <div class="One"></div>
  <div class="Two"></div>
</div>
<div class="B">
  <div class="Three"></div>
</div>

From the top view

From the side view

Lear more about the stacking context:

Mattia Astorino
  • 1,396
  • 14
  • 18
0

Yes, we can ;)... if orange gets a higher z-index than green...

.two {
   ...  
   z-index: 12;
}

It's because pink is a child of orange...

biberman
  • 5,606
  • 4
  • 11
  • 35