z-index 不适用于固定位置

问题描述 投票:0回答:4

我有类似以下的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 索引。

但是我已经为

#link
分配了更高的 z 索引,但它没有进入更高层。

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

jsfiddle

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

css
4个回答
8
投票

为什么固定的位置会遮挡图层(z-index)?

这是因为堆叠上下文。 CSS 定位并向元素添加

z-index
值会创建一个新的堆叠上下文。

来自 MDN 页面

注意: 堆叠上下文的层次结构是 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
投票

您想要链接悬停#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;
}
<div id="one">
    <div id="overlay"></div>
</div>
<div id="two">
    <a href="#" id="link">test</a>
</div>
    

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


0
投票

您需要将

z-index
添加到包装器
div

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

0
投票

因为

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

© www.soinside.com 2019 - 2024. All rights reserved.