z-index chrome bug

时间:2012-10-22 20:18:30

标签: css google-chrome z-index

我遇到了一个非常讨厌的错误,似乎只发生在Windows和OS X上:父级具有固定位置的元素的z-index在Chrome上不起作用!我把奇怪的情况转换成了一个简单的代码:

HTML:

<div id="mask">
    &nbsp;
</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, 0, 0.5);
    width: 100%;
    height: 100%;
    z-index: 9998;
}

.circle {
    position: relative;
    background-color: rgba(255, 204, 0, 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浏览器上进行了测试,它确实有效!

我想知道是否有人知道解决此问题的任何修复方法!

7 个答案:

答案 0 :(得分:12)

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

这意味着永远不会将999899999997进行比较,以确定堆叠顺序。相反,99999997进行比较,以确定.above-mask.below-mask中的哪一个位于前方,然后#box内的所有内容都堆叠在该上下文中,它被视为z-index 0的单个图层,在z-index #mask处堆叠在9998后面。

这也解释了为什么@ TheNextBillGates在#mask内移动#box的答案有效 - 因为#mask.above-mask.below-mask处于同一堆叠环境中。我强烈推荐上述链接以获取更全面的详细信息,您还应该看到the announcement for the stacking change for fixed elements in Chrome

答案 1 :(得分:1)

我刚刚遇到了这个错误,它仍然在Google Chrome v26中发生。我可以在代码或Chrome的CSS编辑器中将z-index设置为我想要的高度,并且它没有任何区别(并且元素的位置设置为绝对值)。在Firefox甚至IE8-IE10中,相同的z-index设置正如预期的那样工作。当我将父元素从position:fixed更改为position:absolute时,子元素的z-index在Chrome中运行良好。

答案 2 :(得分:1)

如果您移动#mask内的#box,则可以正常使用。

<div id="box">
    <div id="mask">&nbsp;</div>
    <div class="below-mask circle">should be below the mask</div>
    <div class="above-mask circle">should be above the mask</div>
</div>

这是一个小提琴http://jsfiddle.net/TheNextBillGates/jKm4b/

不确定为什么会这样。

答案 3 :(得分:0)

将z-index分配给固定div。这应该会导致chrome尊重所有孩子的z-index值。

答案 4 :(得分:0)

多个z-index堆栈在我看来是不幸和令人困惑的,但是如果你提高任何目标元素父项的z-index,你可以在不改变你的html结构的情况下解决这个问题。尝试找到一个父元素,它是与您的内容重叠的麻烦元素的兄弟。应用此样式:

position: relative; z-index: [# higher than overlapping element's z-index];

您的milage可能会因您的项目而异,但此解决方案适用于我的项目。

答案 5 :(得分:0)

我认为它是因为它不像模态窗口那样位于页面底部。简单的解决方法就是抓住所有的模态窗口,然后在结束体标记之前将它们放入div中。下面的示例修复了我遇到的每个chrome问题。

$('body').append('<div id="modelContainer" />');
$('.modal').each(function() {
  $(this).appendTo('#modelContainer');
})

答案 6 :(得分:-1)

更改或删除position: fixed上的#box,您已设置。

jsFiddle

相关问题