CSS: z-index demo

In the project I'm currently developing I've started using the CSS z-index property like never before. This property allows you to create a multi-layer layout using CSS positioning. To see this property in action, elements must overlap. By default, when an overlapping occurs browsers tend to stack the latest element in the source before other positioned elements. But if you specify a numeric index for each element, you can control the layering process.

Elements with a greater z-index value will be displayed above other elements. So if you have three elements, you can specify 3 for the first, 2 for the second and 1 for the third. By doing so, elements will be displayed one on the top of the other following the precedence specified earlier. Let's do an example. We want to create some presentational effects on an image gallery where all the images are positioned and have a specified z-index order:

#gallery {
 width: 600px;
 height: 300px;
 margin: 0 auto;
 position: relative;
}

#gallery img {
 display: block;
 width: 250px;
 height: 180px;
 position: absolute;
 cursor: pointer;
}

#gallery img.center {
 top: 50%;
 left: 50%;
 margin: -75px 0 0 -90px;
 z-index: 3;
}

#gallery img.center:hover {
 z-index: 0;
}

#gallery img.left {
 top: 20px;
 left: 100px;
 z-index: 2;
 -moz-transform: rotate(10deg);
 -webkit-transform: rotate(10deg);
 -o-transform: rotate(10deg);
}

#gallery img.left:hover {
 z-index: 4;
}

#gallery img.right {
 top: 20px;
 right: 100px;
 z-index: 1;
 -moz-transform: rotate(-10deg);
 -webkit-transform: rotate(-10deg);
 -o-transform: rotate(-10deg);
}

#gallery img.right:hover {
 z-index: 4;
}

When you hover an image, its z-index changes so that the current image will be always displayed on the top of the other. In fact, 4 is the greatest value in the current element set. The center image, instead, will have the lowest index available in the current set. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.