问题
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?
回答1:
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.
回答2:
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>
来源:https://stackoverflow.com/questions/14491859/does-position-fixed-create-a-new-stacking-context-for-z-indicies