但是,根据文章What No One Told You About Z-Index:
If an element is contained in a stacking context at the bottom of the stacking order,there is no way to get it to appear in front of another element in a different stacking context that is higher in the stacking order,even with a z-index of a billion!
New stacking contexts can be formed on an element in one of three ways:
- When an element is the root element of a document (the element)
- When an element has a position value other than static and a z-index value other than auto
- When an element has an opacity value less than 1
以下示例:
HTML:
<div><span class="red">Red</span></div> <div><span class="green">Green</span></div> <div><span class="blue">Blue</span></div>
还有一些CSS
.red,.green,.blue { position: absolute; } .red { background: red; } .green { background: green; } .blue { background: blue; }
如果第一个div被赋予不透明度:.99;(它在第一个节点上创建一个new stacking context),那么即使.red有z-index:1,它仍然会被放置在其他元素的后面,因为它只是渲染为该堆栈内的最高元素.
看起来像这样:
解决方法
Q: Is there a way for an element to ignore the stack context of any of it’s parent elements and ask to be positioned relative to the original stack context of the page?
不,不可能在堆栈上下文之间传输定位元素,而不必在DOM中重新定位元素.您甚至不能通过使用position:fixed或position:absolute来移动元素到根堆叠上下文(如您所观察到的那样,.red相对于其父代定位,div:first-child,因为它创建了一个新的堆叠上下文).
话虽如此,鉴于您的HTML和CSS,应该很简单,只是将类重新分配给div元素,如其他答案和here所示,所以您的div和span都参与根堆栈上下文:
<div class="red"><span>Red</span></div> <div class="green"><span>Green</span></div> <div class="blue"><span>Blue</span></div>
但你的情况可能不像看起来那么简单.