Wednesday, 15 June 2011

CSS z-index - how it works?

z-index goes hand-in-hand with the local stacking context. What is a stacking context? Whenever you specify a z-index, you create a new stacking context. Here's an example:

CSS:

body {
margin: 0;
padding: 0;
}
/* generic style */
div.tile {
position: absolute;
border: 1px solid black;
background: white;
width: 4em;
height: 4em;
}
/* box One */
.a {
top: 0;
left: 0;
}
/* box Two */
.b {
top: 1em;
left: 1em;
}
/* box Three */
.c {
top: 2em;
left: 2em;
z-index: -1;
}
/* box Four */
.d {
top: 3em;
left: 3em;
}
/* box Five */
.e {
top: 4em;
left: 4em;
}

HTML

<div style="position: absolute; z-index: 0;">
<div class="tile a">One</div>
<div class="tile b">Two</div>
<div class="tile c">Three</div>
<div class="tile d">Four</div>
</div>
<div class="tile e">Five</div>

So here we have three stacking contexts, the root of the document (<html>), the plain div, and box Three (.c).

When you specify a z-index, that z-index is the offset relative to the current stacking level.

When the z-index on the plain div is 0, boxes One, Two, Four, and Five stack on top of each other sucessively. Since box Three has a negative z-index it is rendered behind boxes One, Two, and Four, and Five. The stacking order from bottom to top is: 3, 1, 2, 4, 5

If you give the z-index on the plain div a 1, boxes One, Two, Three and Four are rendered in front of box Five (change the position and size of box five, go ahead), but box Three is rendered behind boxes One, Two, and Four, due to its negative z-index. The stacking order from back to front is: 5, 3, 1, 2, 4

If you remove the z-index on the plain div, boxes One, Two, Four, and Five are rendered sucessively on top of each other, and box Three is rendered behind the root stacking context (the html element) and cannot be seen. The stacking order from bottom to top is: 3, root, 1, 2, 4, 5)

CSS Version: CSS2

JavaScript syntax: object.style.zIndex="1"

click here to read the original document.

Read about z-index on wwww.w3schools.com

wwww.w3schools.com example

You can also copy the above CSS and HTML to wwww.w3schools.com "Try It" editor and play with it.

No comments:

Post a Comment