1

Background

I've learned z-index working with stacking-context https://drafts.csswg.org/css2/#elaborate-stacking-contexts

And there are a lot of properties that can make stacking-context. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

But I've noticed stacking context does not work with positoin: relative child and opacity: 0.9 child.

In my code example, the blue box behind the red box. But if I uncomment position: relative; z-index is worked fine what I wanted.

Question

What is the difference make stacking context with position / opacity or transform?

section {
  width: 50%;
  height: 200px;
}

.box {
  width: 400px;
  height: 200px;
  background: blue;
  z-index: 5;
  /* Worked! */
  /* position: relative; */
  
  /* Not Worked */
  opacity: 0.9;
  /*   transform: translate(10px, 10px); */
}

.box-2 {
  width: 200px;
  height: 200px;
  background: red;
  margin-top: -50px;
  border: 5px solid black;
  position: absolute;
  z-index: 1;
}
<section>
  <div class="box"></div>
  <div class="box-2"></div>
</section>
sundicide
  • 11
  • 2
  • "What is the difference make stacking context with position / opacity or transform?" - Nothing. But if you want an explanation from me, you'll have to put the code in the question, not solely a link to an external resource. – Alohci Mar 29 '22 at 11:49
  • Thanks Alohci! Add a code snippet to my question. – sundicide Mar 29 '22 at 13:35
  • 1
    z-index works with positioned element, you are confusing *positioned element* with *stacking context* – Temani Afif Mar 29 '22 at 14:42
  • Positioned elements, opacity, and transform create a stacking context _for their children_. They don't affect the stacking context of the element to which they are applied. Plus what Temani said. – Alohci Mar 29 '22 at 15:14
  • Thanks for the comments TemaniAfif, Alohci. It seems there is a difference in work with z-index. Positioned elements make stacking context for children and work with z-index at the same time. But other properties(opacity, transform ...) makes only stacking context, not work with z-index itself. – sundicide Mar 29 '22 at 15:39

0 Answers0