我遇到了一个非常烦人的错误,似乎只发生在
Windows和OS X上:父级具有固定位置的元素的z-index在Chrome上不起作用!我将奇怪的情况转换为简单的代码:
HTML:
- <div id="mask">
-
- </div>
- <div id="Box">
- <div class="below-mask circle">
- should be below the mask
- </div>
- <div class="above-mask circle">
- should be above the mask
- </div>
- </div>
CSS:
- body {
- font-family: Verdana;
- font-size: 9px;
- margin: 0px;
- }
- #Box {
- position: fixed;
- }
- #mask {
- position: absolute;
- left: 0px;
- top: 0px;
- background-color: rgba(0,0.5);
- width: 100%;
- height: 100%;
- z-index: 9998;
- }
- .circle {
- position: relative;
- background-color: rgba(255,204,0.75);
- border-radius: 75px;
- line-height: 150px;
- margin: 50px;
- text-align: center;
- width: 150px;
- height: 150px;
- }
- .above-mask {
- z-index: 9999;
- }
- .below-mask {
- z-index: 9997;
- }
沙箱:http://jsfiddle.net/gibatronic/umbgp/
我在OS X和Windows上的Internet Explorer 9,Firefox 15,Opera 12.02和Safari 5.1.7上进行了测试,所有这些都按预期显示.
我还在Ubuntu 12.10上进行了测试,它适用于包括Chrome在内的所有浏览器!
我甚至在Kindle 4浏览器上测试过它的功能!
解决方法
one800higgins的答案是正确的.真正的答案是
on mobile WebKit and Chrome 22+,
position: fixed
always creates a new stacking context,even when z-index
is auto
.所以堆叠上下文层次结构如下所示:
>文档根(z-index 0)
> #mask(z-index 9998)
> #Box(z-index 0)
> .above-mask(z-index 9999)
> .below-mask(z-index 9997)
这意味着9998永远不会与9999或9997进行比较来确定堆叠顺序.相反,将9999与9997进行比较以确定.above-mask和.below-mask中的哪一个位于前面,然后一旦#Box内的所有内容都堆叠在该上下文中,它将被视为z-index 0处的单个层.在z-index 9998处被堆叠在#mask后面.
这也解释了为什么@ TheNextBillGates在#Box内移动#mask的答案 – 因为#mask与.above-mask和.below-mask处于相同的堆叠上下文中.我强烈推荐以上链接以获取更全面的详细信息,您还应该看到the announcement for the stacking change for fixed
elements in Chrome.