Guy
Guy

Reputation: 167

css z-index issue with nested elements

I have 3 HTML elements that I want to order on the z plane:

.bank {
  width: 200px;
  height: 200px;
  background-color: grey;
  position: absolute;
  
  z-index: 100;
  
  transform: translateY(10%);
}

.card {
  width: 100px;
  height: 100px;
  background-color: red;
  
  position: absolute;
  left: 50px;
  top: 50px;
  
  z-index: 300;
}

.button {
  width: 50px;
  height: 50px;
  background-color: green;
  
  position: absolute;
  left: 30px;
  top: 50px;
  
  z-index: 200;
}
<div class="bank">
       bank
       <div class="card">card</div>
    </div>
    
    <div class="button">button</div>

I want the button to be on top of the bank but behind the card. But the button is always on top of both the bank and the card no matter what I try.

Edit: I noticed that removing z-index and transform from '.bank' solves it, but I need the transform property. What can I do?

What may cause it not to work? Thanks

Upvotes: 2

Views: 2789

Answers (2)

Temani Afif
Temani Afif

Reputation: 273010

Don't specify any z-index to .bank to avoid creating new stacking context and simply adjust the z-index of the other elements. This will work because all the 3 elements belong to the same stacking context so you can specify any order you want.

.bank {
  position:relative;
  background: red;
  width: 500px;
  height: 200px;
}

.card {
  position: absolute;
  top:0;
  z-index: 2;
  height: 100px;
  width: 400px;
  background: blue;
}

.button {
  position: absolute;
  top: 0;
  z-index: 1;
  height: 150px;
  width: 450px;
  background: yellow;
}

.container {
  position: relative;
}
<div class="container">
  <div class="bank">
    <div class="card"></div>
  </div>

  <div class="button"></div>
</div>

UPDATE

Considering you code, the only way is to remove the z-index and transform from .bank or it will be impossible because your elements will never belong to the same stacking context. As you can read in the previous link:

Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.

Related for more details: Why can't an element with a z-index value cover its child?

Upvotes: 5

Nacorga
Nacorga

Reputation: 526

You can do this by adding z-index only to card class and placing the elements in absolute.

.bank {
  width: 150px;
  background: red;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
}

.card {
  width: 50px;
  background: black;
  height: 50px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

.button {
  width: 100px;
  background: blue;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="bank">
   <div class="card"></div>
</div>

<div class="button"></div>

Upvotes: 1

Related Questions