【问题标题】:z-index not working for fixed elementz-index 不适用于固定元素
【发布时间】:2016-02-14 04:05:20
【问题描述】:
当我偶然发现这个有趣的事实时,我正在编写我的代码:
z-index 不适用于固定元素,因此固定元素将始终位于前面。
有没有办法将非固定元素放在固定元素前面?
谢谢。
#fixed {
background-color: red;
width: 500px;
height: 500px;
position: fixed;
z-index: 0;
}
#normal {
background-color: blue;
width: 500px;
height: 500px;
z-index: 1;
}
<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>
【问题讨论】:
标签:
html
css
z-index
fixed
【解决方案1】:
除非您正在处理弹性项目或网格项目,否则必须为z-index 定位元素。1
换句话说,position 属性的值必须不是static,否则z-index 将被忽略。2
您的第二个 div 未定位。这里有两个选项:
- 将
position: relative 添加到#normal,或
- 给定位的 div 一个负的
z-index 值
#fixed {
background-color: red;
width: 500px;
height: 500px;
position: fixed;
z-index: 0; /* a negative value here will also work */
}
#normal {
background-color: lightblue;
width: 500px;
height: 500px;
z-index: 1;
position: relative; /* new */
}
<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>
另请参阅:Basics of the CSS z-index property
1 虽然z-index(在CSS 2.1 中定义)仅适用于定位元素,但CSS 3 允许z-index 与grid items 和flex items 一起使用,即使@987654338 @ 是static。
2z-index property page at MDN
【解决方案2】:
对固定元素使用否定的z-index。
<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>
#fixed {
background-color: red;
width: 500px;
height: 500px;
position: fixed;
z-index: -1;
}
#normal {
background-color: blue;
width: 500px;
height: 500px;
z-index: 1;
}
【解决方案3】:
#fixed {
background-color: red;
width: 500px;
height: 500px;
position: fixed;
z-index: 0;
}
#normal {
background-color: blue;
width: 500px;
height: 500px;
z-index: 1;
position:relative;
}
<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>
#fixed {
background-color: red;
width: 500px;
height: 500px;
position: fixed;
z-index: 0;
}
#normal {
background-color: blue;
width: 500px;
height: 500px;
z-index: 1;
position:relative;
}
<div id = 'fixed'> I'm Fixed </div>
<div id = 'normal'> I'm Normal </div>