Search code examples
cssz-index

CSS make child to topmost using z-index


https://codepen.io/anon/pen/QZVVbY

I want the code above of the green box to be topmost.

But apparently, it's under another small z-index container.

I don't want to change parent z-index. How to achieve this?

Not to change the z-index of parent and other parent

.container{
  width: 500px;
  height: 50px;
}

.container1 {
  background: red;
  width: 500px;
  height: 50px;
  position: relative;
  z-index: 2;
}
.container2 {
  background: blue;
  width: 50px;
  height: 50px;
  position: relative;
}
.container3 {
  background: green;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 30px;
  left: 20px;
  z-index: 2200000;
}
.container4 {
  background: yellow;
  width: 500px;
  height: 50px;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 5;
}
.container5 {
  background: gray;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 15px;
  left: 40px;
}
<div class="container1">
  <div class="container2"></div>
  <div class="container3"></div>
</div>

<div class="container4">
  <div class="container5"></div>
</div>


Solution

  • The issue is that having a z-index on container1 is creating a layer stack. This results in all child elements with a z-index to be relative to the parents z-index. In order to make this work removing the z-index style from container will get the effect you're wanting.

    .container{
      width: 500px;
      height: 50px;
    }
    
    .container1 {
      background: red;
      width: 500px;
      height: 50px;
      position: relative;
    }
    .container2 {
      background: blue;
      width: 50px;
      height: 50px;
      position: relative;
    }
    .container3 {
      background: green;
      width: 50px;
      height: 50px;
      position: absolute;
      top: 30px;
      left: 20px;
      z-index: 999999;
    }
    .container4 {
      background: yellow;
      width: 500px;
      height: 50px;
      position: absolute;
      top: 0;
      left: 20px;
      z-index: 5;
    }
    .container5 {
      background: gray;
      width: 50px;
      height: 50px;
      position: absolute;
      top: 15px;
      left: 40px;
    }
     
    <div with z-index=1 class="container1" >
        <div class="container2"></div>
        <div with z-index=100 class="container3" ></div>
    </div>
    
    <div with z-index=2 class="container4" >
      <div class="container5"></div>
    </div>