z-index not working for fixed element

你。 提交于 2019-12-12 10:54:33

问题


I was working on my code when I stumbled upon this fun fact:

z-index doesn't work for a fixed element and, therefore, fixed elements will always be in front.

Is there a way to place a non-fixed element in front of a fixed element?

Thanks.

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

回答1:


Unless you're dealing with flex items or grid items, an element must be positioned for z-index to work.1

In other words, the position property must have a value other than static or z-index will be ignored.2

Your second div is not positioned. Here are two options:

  • add position: relative to #normal, or
  • give the positioned div a negative z-index value

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

See also: Basics of the CSS z-index property


1 Although z-index, as defined in CSS 2.1, applies only to positioned elements, CSS 3 allows z-index to work with grid items and flex items, even when position is static.

2 z-index property page at MDN




回答2:


Use negative z-index for the fixed element.

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


来源:https://stackoverflow.com/questions/35388228/z-index-not-working-for-fixed-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!