2016-02-14 10 views
5

ich auf meinem Code arbeite, als ich auf diese Spaß Tatsache gestolpert:z-index nicht für festes Element arbeitet

z-index nicht für ein festes Element arbeiten, und deshalb werden feste Elemente vor immer .

Gibt es eine Möglichkeit, ein nicht fixiertes Element vor einem festen Element zu platzieren?

Danke.

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

Antwort

7

Sofern Sie mit Flexelemente oder Rasterelemente zu tun hat, muss ein Element für z-index arbeiten positioniert werden.

Mit anderen Worten muss die position Eigenschaft einen anderen Wert haben als static oder z-index werden ignoriert.

Ihr zweites Div ist nicht positioniert. Hier sind zwei Möglichkeiten:

  • hinzufügen position: relative-#normal oder
  • geben dem positioniert div einen negativen z-index Wert

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

Siehe auch: Basics of the CSS z-index property


z-index Obwohl, wie in CSS 2.1 definiert ist, bezieht sich nur auf positionierte Elemente, CSS 3 z-index ermöglicht mit grid itemsflex items und zu arbeiten, auch wenn positionstatic ist.

z-index property page at MDN

1

Verwenden negativen z-index für das feststehende 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; 
} 
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>

Verwandte Themen