3

For instance, take the following HTML & CSS:

<div class="fixed"></div>
<div class="wrapper">
  <div class="child"></div>
</div>

.fixed {
  background: blue;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 2;
}

.wrapper, .child {
  position: absolute;  
  height: 20px;
  width: 20px;
  padding: 20px;
}

.wrapper {
  z-index: 1;
  background: red;
}

.child {
  position: absolute;
  z-index: 3;
  background: yellow;
}

Expected behaviour would be that .child displays above .fixed whilst .wrapper is invisible however on http://jsfiddle.net/STLMR/ .fixed shows above all (tested in Chrome + Firefox). Is there some trick to this, or is there some quirk of CSS I'm missing?

DanH
  • 5,498
  • 4
  • 49
  • 72

2 Answers2

4

In CSS, z-index is not absolute, but relative to the parent container. With "absolute" I'm not referring to the position: absolute attribute, I state this because it might be confusing.

Related: https://stackoverflow.com/a/7490187/671092

Community
  • 1
  • 1
gd1
  • 11,300
  • 7
  • 49
  • 88
  • Well TIL, that explains probably a lot of headaches over the last few years, thanks! So my only option is to either move `.child` out of `.wrapper`, or put `.fixed` inside `.wrapper`? – DanH Jan 07 '13 at 15:28
  • Yes moving `.fixed` into `.wrapper` seems to support this, http://jsfiddle.net/STLMR/4/ – DanH Jan 07 '13 at 15:28
  • Actually that has other obvious side effects given my actual use case has much more complex HTML, but I'm definitely much closer – DanH Jan 07 '13 at 15:31
  • I removed `z-index` and it still works as expected (Firefox 78): http://jsfiddle.net/DmitryMyadzelets/1k5pqny6/ – Dmitry Apr 10 '21 at 09:02
2

You have to move the .child into a new container that has a higher z-index than .fixed.

PaperThick
  • 2,749
  • 4
  • 24
  • 42