css - 覆盖 CSS Z-Index 堆叠上下文

标签 css z-index

我正在尝试覆盖/忽略元素的堆叠上下文,以便它可以定位在相对于页面根的 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 .redz-index:1,它仍将位于其他元素之后,因为它只是作为该堆栈中最高的元素呈现。

Working Demo in jsFiddle

看起来像这样:

demo

:有没有办法让元素忽略其任何父元素的堆栈上下文并要求相对于页面的原始堆栈上下文进行定位?

最佳答案

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: fixedposition: absolute 将元素移动到根堆栈上下文(如您所见,.red 是相对于其父级 div:first-child 定位,因为它创建了一个新的堆叠上下文)。

也就是说,鉴于您的 HTML 和 CSS,只需将类重新分配给 div 元素应该是微不足道的,如其他答案和 here 所示。所以你所有的 divspan 都参与根堆栈上下文:

<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/

相关文章:

javascript - 难倒未捕获的语法错误 : Unexpected token else,

javascript - IE 11 上的 Bootstrap 和 JQuery 布局异常

css - 菜单在表格第一个固定列中的位置(z-index)

Flash 视频在 IE7 中的所有其他内容之上播放

javascript - famo.us Firefox 设置 z-index 不起作用

javascript - Z-index 不适用于 jquery css

css - 文本区域中的垂直对齐

javascript - 如何同时添加和删除类?

javascript - jquery mobile 根据内容大小对齐按钮

jquery - 自动完成 jquery UI 无法使用华丽的弹出 jquery 对话框