HTML and CSS

Z-index

The z-index creates the dimensional axis upon which you can "stack" and overlap items. This comes in handy in positioning because you can use it to determine which boxes come to the foreground and which ones will flow behind upon browser resize. Other uses for the z-index relate mostly to DHTML, in which element boxes are scripted for dynamic purposes such as when creating animations or games.

Example 12-10 shows three boxes, each absolutely positioned to overlap one another and styled in such a way that you can visualize the stacking order.

Example 12-10. Z-index with positioned boxes
#box1 {
          position: absolute;
          top: 10px;
          left: 10px;
          background: #000;
          width: 300px;
          height: 200px;
          z-index: 1;
          }

#box2 {
          position: absolute;
          top: 20px;
          left: 20px;
          background: #999;
          width: 300px;
          height: 200px;
          z-index: 2;
          }

#box3 {
          position: absolute;
          top: 30px;
          left: 30px;
          background: #ccc;
          width: 300px;
          height: 200px;
          z-index: 3;
          }

You'll note that the higher the number is, the "closer" the box appears in the stack. So, a box with a z-index of 3 appears to be the closest to you in the stack (see Figure 12-16).

Figure 12-16. Z-index and stacking orderthe higher the integer value is, the closer to you in the stack the element appears.

Just Like a Pro…

If it's taking a bit of time to get the concepts in this tutorial down, please don't fret. These are some of the most complicated, confusing, and challenging aspects of CSS.

There's really no way to comfort you if you are having a bit of trouble, other than to say that you must give it time. No one learns this stuff overnightand if you have, well, you're ready for prime time!

It takes constant practice and play to really get the hang of working with positioning; it's simply part of the nature of the CSS beast.

Of course, the rewards are richly worth it. As you'll find out in the next tutorial, everything in this tutorial will come togetherat least, conceptuallywhen you begin to study layouts. After that, you'll want to practice, practice, practice to really get your skills as finely honed as a pro's.

by BrainBellupdated
Advertisement: