我正在尝试覆盖/忽略元素的堆叠上下文,以便它可以定位在相对于页面根的 z 轴上。
然而,根据文章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
用下面的例子:
.red, .green, .blue { position: absolute; }
.red { background: red; }
.green { background: green; }
.blue { background: blue; }
<div><span class="red">Red</span></div>
<div><span class="green">Green</span></div>
<div><span class="blue">Blue</span></div>
如果第一个 div 被赋予 opacity:.99;
,(在第一个节点上创建一个 new stacking context)那么即使 if .red
有z-index:1
,它仍将位于其他元素之后,因为它只是作为该堆栈中最高的元素呈现。
Working Demo in jsFiddle
看起来像这样:
问:有没有办法让元素忽略其任何父元素的堆栈上下文并要求相对于页面的原始堆栈上下文进行定位?
最佳答案
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>
但您的情况可能并不像看起来那么简单。
关于css - 覆盖 CSS Z-Index 堆叠上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19850037/