CSS Tutorial: Setting the Z-Index Order (OMG the Web in 3D)

by Matt on April 28th, 2009

I’ve been getting a few hits on my site about creating an overlapping, tabbed horizontal navigation, but a lot of searchers just want to know about setting the z-index order to overlap elements. Here’s a nuts and bolts tutorial. HTML & CSS code is at the bottom.

Let’s say you have these two boxes…

…and you want to overlap one on top of the other. To do so you must set two properties: z-index and position. If you want to use the z-index property, you are required to change the element’s position property.

For the sake of this nuts-n-bolts demonstration I’m going to set both Orange and Purple’s position to relative. First I’ll move Purple up, so I’m going to set its position to relative, and its top property to -10px. I’m also going to move it over 10px horizontally (left: 10px) so that you can see where it is in relation to Orange.

See how Purple’s box is on top of Orange? That behavior is, by default, a matter of their linear order in the HTML (purple comes after orange, so it’s on top). Note that you don’t have to set Purple’s z-index to achieve this effect, but to emphasize the behavior it is recommended that you put “z-index: 1″ in Purple’s styling (IF this is your desired outcome). If, however, you want Orange on top then you must set Orange’s z-index to 1. This is reflected in the demo and code below:

The Code

< style type = "text/css" >
     #demo_box_orange { z-index: 1; position: relative; width: 40px; height: 40px; border: 1px solid blue; background-color: orange; }
     #demo_box_purple { position: relative; top: -10px; left: 10px; width: 40px; height: 40px; border: 1px solid green; background-color: purple; }
< /style >
< div id="demo_box_orange" >< /div >
< div id="demo_box_purple" >< /div >

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS