How To Use Z Index in CSS

Apr 25, 2012, by admin

By default, the elements of a website line themselves up next to or under each other automatically. However, at times, the design needs them to overlie. When that happens, the stacking order becomes vital, and the natural stacking order will need to be influenced.
Without applying any CSS to the elements within the wrapper on the demo page here, this code:

<body>

<div id=”wrapper”>

<img id=”aqua” src=”aqua.gif” alt=”aqua square”>

<img id=”green” src=”green.gif” alt=”green square”>

<h1>The z-index and CSS — When the Stacking Order Matters</h1>

<h2>All elements appear in their natural order as they are entered in the HTML</h2>

</div>

</body>

creates a page that looks like this. As you see, there is no point worrying about piling order, the elements alien themselves automatically.
However, when placing is applied and they start overlapping, we can change their piling order if we need to. When it comes to z-index and the stacking order, one must note the following:

1.Z-index only works on relative or absolute placed elements
2.The default z-index is zero
Here, I have added an complete place to the h1 and a relative location to the green box to move them up and down-and-left, correspondingly.

h1 {

position: absolute;

top: 100px;

left: 100px;

}

 

#green {

position: relative;

top: 50px;

left: -50px;

}

 

h2 {margin-top: 50px;} /*This is here to push the line below the green box */

That means that the aqua image, which does NOT have positioning applied, sits on the default level of zero. Adding any kind of z-index to the element is useless – it won’t budge because of the lacking positioning. But we can move the text and the box either under (with a negative z-index) or on top (with a positive z-index) the not-positioned, zero-level aqua box.

#green {

position: relative;

top: 50px;

left: -50px;

z-index: -2;

}

h1 {

position: absolute;

top: 100px;

left: 100px;

z-index: -1;

}

creates this page.