Z-index does not work for fixed element

I was working on my code when I came across this funny fact:

z-index does not 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> 
+5
source share
3 answers

If you are not using flex or grid elements, the element must be positioned for the z-index to work. 1

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

Your second div is not located. 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 z-index CSS Property


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

2 z-index property page in MDN

+7
source

Use a negative z-index for a fixed item.

 <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; } 
+1
source

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

Source: https://habr.com/ru/post/1242968/


All Articles