On the last page, we learned how to place elements “wherever” we want. We even learned how to place elements over other elements, thereby, blocking those elements.
The z-index property allows developers to specify which elements should be placed on top of other elements. The z-index property takes an integer number as its value (i.e. -1000 to 1000). Those elements with higher z-index values will be drawn on top elements with lower values.
The following example comes from an article on the Mozilla Developers Network.
Notice a few things about this example.
DIV #1
was given a position value of absolute
and z-index: 5
.
DIV #5
. That is because the yellow element did not have a position property setting.DIV #4
is also placed on top of the yellow DIV #5
element.DIV #2
is placed on top of DIV #4
since it has a higher z-index, but underneath DIV #1
.DIV #3
was placed underneath all other elements, even the yellow DIV #5
.
-2
).DIV #3
, even though DIV #3
cannot be placed above other elements with position values specified.<div id="absdiv1">
<br /><span class="bold">DIV #1</span>
<br />position: absolute;
<br />z-index: 5;
</div>
<div id="reldiv1">
<br /><span class="bold">DIV #2</span>
<br />position: relative;
<br />z-index: 3;
</div>
<div id="reldiv2">
<br /><span class="bold">DIV #3</span>
<br />position: relative;
<br />z-index: -2;
</div>
<div id="absdiv2">
<br /><span class="bold">DIV #4</span>
<br />position: absolute;
<br />z-index: 1;
</div>
<div id="normdiv">
<br /><span class="bold">DIV #5</span>
<br />no positioning
<br />z-index: 8;
</div>
div {
opacity: 0.7;
font: 12px Arial;
}
span.bold { font-weight: bold; }
#normdiv {
z-index: 8;
height: 70px;
border: 1px dashed #999966;
background-color: #ffffcc;
margin: 0px 50px 0px 50px;
text-align: center;
}
#reldiv1 {
z-index: 3;
height: 100px;
position: relative;
top: 30px;
border: 1px dashed #669966;
background-color: #ccffcc;
margin: 0px 50px 0px 50px;
text-align: center;
}
#reldiv2 {
z-index: -2;
height: 100px;
position: relative;
top: 15px;
left: 20px;
border: 1px dashed #667399;
background-color: #ccf1ff;
margin: 0px 50px 0px 50px;
text-align: center;
}
#absdiv1 {
z-index: 5;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
left: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
text-align: center;
}
#absdiv2 {
z-index: 1;
position: absolute;
width: 150px;
height: 350px;
top: 10px;
right: 10px;
border: 1px dashed #990000;
background-color: #ffdddd;
text-align: center;
}
[View on GitHub] | [Live Example] |