z-index不适用于固定位置

时间:2014-08-27 10:21:14

标签: css

我有类似下面的css:

#one{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
}
#two{
    position: relative;
    z-index: 9;
    width: 200px;
    height: 200px;
    background: red;
}
#link{
    position: relative;
    z-index: 9999999; /*this is not in higher layer why??? */
}

根据我的设计,我无法增加#two的z-index。

但是我已经为#link分配了更高的z-index,但它没有进入更高层。

那么,为什么固定的位置阻塞了图层(z-index)?

jsfiddle

如果#one的位置没有固定,那么它可以正常工作。所以,我的问题是为什么固定位置给我一个错误?

4 个答案:

答案 0 :(得分:1)

  

为什么固定的位置阻塞了图层(z-index)?

这是因为The stacking context。 CSS定位并向元素添加z-index值会创建新的堆叠上下文。

来自MDN page

  

注意:堆叠上下文的层次结构是HTML元素层次结构的一个子集

因此,在您的特定情况下:

<div id="one">
    <div id="overlay"></div>
</div>
<div id="two">
    <a href="#" id="link">test</a>
</div>

堆叠上下文的层次结构将是:

    • #one
    • #two
      • #link

#link无论#one值是多少,都会置于z-index之下。

一个选项是增加z-index元素的#two值(超过#one)。

答案 1 :(得分:0)

您需要将z-index添加到包装器div

#two{
    position: relative;
    z-index: 9;
    width: 200px;
    height: 200px;
    background: red;
    z-index: 9999;
}
#link{
    position: relative;
}

答案 2 :(得分:0)

因为#link&#39; z-index#two相关(#link的父亲){{1然后z-index&#39; s和#one&#39; s #two相对于其父级(在本例中为z-index)。

答案 3 :(得分:0)

你想要链接悬停#two吗? 类似的东西?

#one{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
}
#two{
    position: relative;
    z-index: 2;
    width: 200px;
    height: 200px;
    background: red;
}
#link{
    position: relative;
    z-index: 9999999;
}

http://jsfiddle.net/0q84xq87/1/