2016-02-14 24 views
5

ja pracowałem na moim kodzie, gdy natknąłem się na ten fakt zabawy:z-index nie pracuje na stałym elementem

z-index nie działa na element stały, a więc trwałe elementy zawsze będzie z przodu .

Czy istnieje sposób umieszczenia niezamontowanego elementu przed stałym elementem?

Dzięki.

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

Odpowiedz

7

Chyba że masz do czynienia z zasilaniem flex przedmiotów lub elementów sieci, element musi być umieszczony na z-index do pracy.

Innymi słowy, własność position musi mieć wartość inną niż static lub z-index będą ignorowane.

Twój drugi element div nie jest ustawiony. Tutaj są dwie opcje:

  • dodać position: relative do #normal lub
  • dać pozycjonowanego div negatywny z-index wartość

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

Zobacz także: Basics of the CSS z-index property


Chociaż z-index, jak określono w CSS 2.1, odnosi się tylko do elementów pozycjonowanych, CSS 3 pozwala z-index pracować grid items i flex items, nawet gdy position jest static.

z-index property page at MDN

1

Zastosowanie ujemny z-index na stałym elemencie.

<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; 
} 
0

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