覆盖CSS Z索引堆栈上下文

前端之家收集整理的这篇文章主要介绍了覆盖CSS Z索引堆栈上下文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图覆盖/忽略元素的堆叠上下文,以便它可以相对于页面根位于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

以下示例:

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,它仍然会被放置在其他元素的后面,因为它只是渲染为该堆栈内的最高元素.

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>

但你的情况可能不像看起来那么简单.

原文链接:https://www.f2er.com/css/216873.html

猜你在找的CSS相关文章