Developer

Layer positioned content

CSS positioning uses the z-axis to layer objects on top of each other. Learn how to create 3D layering.

By Matt Rotter, Charity Kahn, and Paul Anderson

Here's the part you've been waiting for: 3D layering! We've already explained how to set your object's x and y coordinates, or its horizontal and vertical positioning. CSS positioning uses the z-axis to layer objects on top of each other. Normally, if you position multiple elements at the same x and y coordinates, each new element will cover up the earlier elements. But with the z-index property, you can specify the layer on which an object lies. By setting the z-index higher or lower, you can move the object up or down in the stack.

In the example below, both lines of text sit at approximately the same absolute location on the page (the second one is placed 10 pixels lower than the first). Normally, the second element would be placed on top of the first element, but we can override this layering by setting the elements' z-index properties.

<HTML>
<HEAD>
<STYLE type="text/css">
<!—
.over { position: absolute;
     top: 165px;
     left: 20px;
     z-index: 2;
     background-color: green
     }

.under { position: absolute;
     top: 175px;
     left: 20px;
     z-index: 1;
     background-color: blue
     }
—>
</STYLE>
</HEAD>
<BODY>

<SPAN class="over">This text is positioned 20 pixels from the left and 165 pixels from the top of the window.</SPAN>

<SPAN class="under">This text is positioned just below the above text, and would usually be placed on top because of its order on the page.</SPAN>
</BODY>
</HTML>

Note: The examples on this page work only with browsers of version 4.0 and later.

Matt Rotter and Charity Kahn are software engineers for CNET.com.

Paul Anderson is an associate technical editor for CNET Builder.com.

Editor's Picks