繁体   English   中英

z-index不适用于固定元素

[英]z-index not working for fixed element

当我偶然发现这个有趣的事实时,我正在处理我的代码:

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> 

除非您正在处理弹性项目或网格项目,否则必须定位一个元素才能使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> 

另请参见: CSS z-index属性的基础知识


1虽然CSS 2.1中定义的z-index仅适用于定位元素,但CSS 3允许z-index处理网格项弹性项 ,即使positionstatic

MDN上的 2个 z-index属性页面

对固定元素使用负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;
}

 #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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM