To change the default stack order positioned elements (position
property set to relative
, absolute
or fixed
), use the z-index
property.
The higher the z-index, the higher up in the stacking context (on the z-axis) it is placed.
In the example below, a z-index value of 3 puts green on top, a z-index of 2 puts red just under it, and a z-index of 1 puts blue under that.
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
div {
position: absolute;
height: 200px;
width: 200px;
}
div#div1 {
z-index: 1;
left: 0px;
top: 0px;
background-color: blue;
}
div#div2 {
z-index: 3;
left: 100px;
top: 100px;
background-color: green;
}
div#div3 {
z-index: 2;
left: 50px;
top: 150px;
background-color: red;
}
This creates the following effect:
See a working example at JSFiddle.
z-index: [ number ] | auto;
Parameter | Details |
---|---|
number | An integer value. A higher number is higher on the z-index stack. 0 is the default value. Negative values are allowed. |
auto | Gives the element the same stacking context as its parent. (Default) |
All elements are laid out in a 3D axis in CSS, including a depth axis, measured by the z-index
property. z-index
only works on positioned elements: (see: Why does z-index need a defined position to work?). The only value where it is ignored is the default value, static
.
Read about the z-index property and Stacking Contexts in the CSS Specification on layered presentation and at the Mozilla Developer Network.