Z-Index-Basics
I'm sure you're familiar with three-dimensional coordinate space. We have an x-axis which is typically used to represent the horizontal, a y-axis to represent the vertical, and a z-axis used to represent what happens into and out of the page, or the screen in our case.
We don't literally see the z-axis, as the screen is a two-dimensional plane. We see it in the form of perspective and of some elements appearing in front of or behind other elements when they share the same two-dimensional space.
To determine where along this third axis an element is located, CSS allows us to set
three values on the z-index property.
- auto ( default )
- integer
- inherit
For the moment let's focus on the integer value. This can be positive, negative, or 0. The greater the value, the closer to the viewer the element appears. The lower the value, the further away it appears.
If two elements are positioned so they both occupy a shared area of two-dimensional space, the element with the greater z-index will obscure or occlude the element with the lower z-index in the areas where they share the space.
HTML
<div class="one">
<div class="two"></div>
<div class="three"></div>
</div>
<div class="four"></div>
CSS
div {
width: 200px;
height: 200px;
padding: 20px;
}
.one, .two, .three, .four {
position: absolute;
}
.one {
background: #f00;
outline: 5px solid #000;
top: 100px;
left: 200px;
z-index: 10;
}
.two {
background: #0f0;
outline: 5px solid #000;
top: 50px;
left: 75px;
z-index: 100;
}
.three {
background: #0ff;
outline: 5px solid #000;
top: 125px;
left: 25px;
z-index: 150;
}
.four {
background: #00f;
outline: 5px solid #ff0;
top: 200px;
left: 350px;
z-index: 50;
}
jsfiddle link
http://jsfiddle.net/K7J35/
Even though div.two has the greater z-index (100), it actually sits below div.four (z-index = 50) on the page. You can see the result of the code above in the image below. The black and yellow borders show the different stacking contexts each element is in.
Since div.two is contained within div.one, its z-index is relative to
div.one
's stack. In effect what we really have is the following:- .one — z-index = 10
- .two — z-index = 10.100
- .three — z-index = 10.150
- .four — z-index = 5
div.one
and everything it contains below div.four
. No matter what values we set on the z-index property of elements inside div.one
they will always display below div.four
.If you're like me, this has probably tripped you up once or twice when working with z-index. Hopefully these examples help clear up why an element with a greater z-index sometimes ends up displaying behind another element with a lower z-index.
Conclusion
When you first encounter it, the z-index property seems like a very simple property to understand. Values represent a location on an axis into and out of the screen, and that's all.