覆盖CSS Z-Index堆叠上下文 [英] Override CSS Z-Index Stacking Context

查看:180
本文介绍了覆盖CSS Z-Index堆叠上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图覆盖/忽略元素的堆叠上下文,因此它可以相对于页根位于z轴上。



但是,根据所示,所有您的 div s和 span 参与根堆叠上下文:

  < div class =red>< span>红色< / span>< / div> 
< div class =green>< span>绿色< / span>< / div>
< div class =blue>< span> Blue< / span>< / div&

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


I'm trying to override / ignore the stacking context for an element so it can be positioned on the z-axis relative to the page root.

However, according to the article 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

With the following example:

HTML:

<div><span class="red">Red</span></div>
<div><span class="green">Green</span></div>
<div><span class="blue">Blue</span></div>

And some CSS

.red, .green, .blue { position: absolute; }
.red   { background: red; }
.green { background: green; }
.blue  { background: blue; }

If the first div is given opacity:.99;, (which creates a new stacking context on the first node) then even if .red has z-index:1, it will still be placed behind the other elements because it is just rendered as the highest element within that stack.

Working Demo in jsFiddle

Which looks like this:

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?

解决方案

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?

No, it's not possible to transfer a positioned element between stacking contexts without repositioning the element in the DOM. You cannot even move an element to the root stacking context by using position: fixed or position: absolute (as you have observed, .red is being positioned relative to its parent, div:first-child because it creates a new stacking context).

That being said, given your HTML and CSS it should be trivial to just reassign the classes to the div elements instead, as shown in other answers and here so all your divs and spans participate in the root stacking context:

<div class="red"><span>Red</span></div>
<div class="green"><span>Green</span></div>
<div class="blue"><span>Blue</span></div>

But your situation probably isn't as simple as it seems.

这篇关于覆盖CSS Z-Index堆叠上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆