【问题标题】:z-index is not working with position fixedz-index 不适用于固定位置
【发布时间】:2014-10-20 21:19:20
【问题描述】:

我有类似下面的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 的位置没有固定,那么它可以正常工作。所以,我的问题是为什么 position fixed 给了我一个错误?

【问题讨论】:

标签: css


【解决方案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 的值是多少。

一种选择是增加#two 元素的z-index 值(大于#one)。

【讨论】:

  • @C-linkNepal fixed 定位不是这样:jsfiddle.net/0q84xq87/2 但是HTML元素的顺序是放在DOM中的。如果您使用relative 定位#one,则计算的高度和宽度将为0,因为它没有任何内容:jsfiddle.net/0q84xq87/3
【解决方案2】:

你想要链接悬停#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/

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 我用粗体字声明我不能按照我的设计增加 #two 的 z-index...
    • z-index 仅适用于相同的图层元素。在上述情况下,它仅适用于#one#two。如果您无法增加#twoz-index,那么您可以为z-index 大于#one 的链接添加单独的包装器
    【解决方案4】:

    因为#linkz-index 是相对于#two 的(这是#link 的父级)z-index 那么#one#twoz-index 是相对的给他们的父母(在这种情况下是body)。

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多