0

My CSS code has two squares, green (small, child) and red (big, parent). I want to hide the lower half of small box under big box so that no overlap is visible.

My following code doesn't work but if I remove z-index on the red box, it works.

I can't understand this behaviour. As per my understanding, any -ve z-index on the child will take it below the parent no matter what the z-index on the parent is. Is it incorrect?

.parent {
  background:red;
  height: 100px;
  width: 100px;
  position: absolute;
  z-index:1;/*comment this line to make it working*/
}

.child {
    height: 10px;
    width: 10px;
    position:absolute;
    background:green; 
    top: 0%;
    left: 50%;
    transform: translateY(-50%);
    z-index: -1;
}
<div class="parent">
    <div class="child"></div>
</div>

Expected result:

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
asdasd
  • 6,050
  • 3
  • 14
  • 32

1 Answers1

2

By giving the parent element a z-index of its own you establish a new stacking context.

This causes the z-index of the child to be scoped to inside the parent instead of scoped to the html element.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335