z-index 不适用于固定位置
Posted
技术标签:
【中文标题】z-index 不适用于固定位置【英文标题】:z-index is not working with position fixed 【发布时间】: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 给了我一个错误?
【问题讨论】:
@Dwza 有一把小提琴 这能回答你的问题吗? z-index not working with fixed positioning 【参考方案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-linkNepalfixed
定位不是这样: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
。如果您无法增加#two
的z-index
,那么您可以为z-index
大于#one
的链接添加单独的包装器【参考方案4】:
因为#link
的z-index
是相对于#two
的(这是#link
的父级)z-index
那么#one
和#two
的z-index
是相对的给他们的父母(在这种情况下是body
)。
【讨论】:
以上是关于z-index 不适用于固定位置的主要内容,如果未能解决你的问题,请参考以下文章