0

The z-index spec makes no special mention of position: fixed, but this fiddle orders elements differently on Chrome 24. Does setting position: fixed create a new stacking context for child elements?

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76

2 Answers2

0

According to this post, Chrome 22+ mimics mobile WebKit's behavior and creates a new stacking context for fixed position elements.

Firefox through at least 17 follows the spec and does not create a new context.

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76
  • To complement, [this](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context) documentation shows all properties that create stacking context. – otaviodecampos Oct 13 '15 at 12:28
0

Here is an example where I have two fixed elements each with its own stacking context. I toggle the second element from fixed position to relative position. When the second element is changed to fixed without specifying its z-index, its child is a new local stacking context with a global z-index of parent which is 0. So, changing the child's z-index has no effect and it remains to be hidden, though it has higher z-index than the other fixed element.

let fixed = false;
function handleClick() {
  const elem = document.getElementById('toggle');
  const buttonElem = document.querySelector('button');
  if (!fixed) {
    elem.className = 'content--fixed';
    fixed = true
    buttonElem.innerText = 'Remove Fixed';
  } else {
    elem.className = 'content';
    fixed = false;
    buttonElem.innerText = 'Add Fixed';
  }
}
body {
  margin: 0;
  padding: 0;
}

.sidebar {
  position: fixed;
  width: 30%;
  background-color: #ccc;
  min-height: 100vh;
  z-index: 500;
}

.content--fixed {
  left: 30%;
  width: 50vw;
  position: fixed;
}

.content {
  padding-left: 30%;
  position: relative;
}

.hover {
  position: absolute;
  background-color: red;
  color: white;
  width: 400px;
  height: 10vh;
  left: -200px;
  z-index: 600;
}

.content .hover {
  left: 100px;
}
<div class="sidebar">
  Sidebar
</div>
<div id="toggle" class="content">
    <button onclick="handleClick()">Add Fixed</button>
  <div class="hover">
    Hover
  </div>
</div>
vijayst
  • 20,359
  • 18
  • 69
  • 113