-1

I have a problem with the following code which is a simplification of a bigger problem.

Could you let me know why if:

.div_A {z-index: 10;} < .div_C {z-index: 20;}

why the button which is inside div_C is behind div_A?

I need to know the exact reason in order to be very specific applying the solution to my bigger problem.

If you can provide me the code fixed (with as fewer changes as you can), it will be really appreciate it.

.button {
 display: inline-block;
 color: #fff !important;
 background-color: #be1e2d;
 text-decoration: none;
 padding: 10px 23px;
}
.div_A {
 display: inline-block;
 position: absolute;
 top: -100px;
 z-index: 10;
}
.div_B {
 position: relative;
 display: inline-block;
 width: 400px;
 height: 400px;
 background-color: #aaf;
 opacity: 0.9;
}
.div_C {
 text-align: center;
 z-index: 20;
}
<div>
 <div class="div_A">
  <div class="div_B"></div>
 </div>
 <div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
 </div>
</div>

Thanks!

David Smith
  • 481
  • 1
  • 5
  • 14
  • [That is due to `Stacking-Context`.](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context) – deEr. May 29 '18 at 18:30

2 Answers2

1

You need a defined position setting other than static for elements to which you apply a z-index to make it have the desired effect. I added position: relative; in the snippe to DIV_C below.

.button {
 display: inline-block;
 color: #fff !important;
 background-color: #be1e2d;
 text-decoration: none;
 padding: 10px 23px;
}
.div_A {
 display: inline-block;
 position: absolute;
 top: -100px;
 z-index: 10;
}
.div_B {
 position: relative;
 display: inline-block;
 width: 400px;
 height: 400px;
 background-color: #aaf;
 opacity: 0.9;
}
.div_C {
 text-align: center;
 z-index: 20;
 position: relative;
}
<div>
 <div class="div_A">
  <div class="div_B"></div>
 </div>
 <div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
 </div>
</div>
Johannes
  • 64,305
  • 18
  • 73
  • 130
-1

You just forgot to put position: absolute; in .div_C

.button {
 display: inline-block;
 color: #fff !important;
 background-color: #be1e2d;
 text-decoration: none;
 padding: 10px 23px;
}
.div_A {
 display: inline-block;
 position: absolute;
 top: -100px;
 z-index: 10;
}
.div_B {
 position: relative;
 display: inline-block;
 width: 400px;
 height: 400px;
 background-color: #aaf;
 opacity: 0.9;
}
.div_C {
 text-align: center;
 z-index: 20;
 position: absolute;
}
<div>
 <div class="div_A">
  <div class="div_B"></div>
 </div>
 <div class="div_C">
        <a href="#" class="button" style="">TRY TO CLICK ME!</a>
 </div>
</div>