Coding All-in-One For Dummies
Book image
Explore Book Buy On Amazon
When you use absolute positioning, you can determine exactly where things are placed, so it’s possible for them to overlap. By default, elements described later in HTML are positioned on top of elements described earlier.

Handling depth in CSS

You can use a special CSS attribute called z-index to change this default behavior. The z-axis refers to how close an element appears to be to the viewer. This image demonstrates how this works.

z-index
The z-index allows you to change which elements appear closer to the user.

The z-index attribute requires a numeric value. Higher numbers mean the element is closer to the user (or on top). Any value for z-index places the element higher than elements with the default z-index. This can be very useful when you have elements that you want to appear on top of other elements (for example, menus that temporarily appear on top of other text).

Here’s the code illustrating the z-index effect:

zindex.html

Working with z-index

The only change in this code is the addition of the z-index property. The higher a z-index value is, the closer that object appears to be to the user.

Here are a couple things to keep in mind when using z-index:

  • One element can totally conceal another. When you start positioning things absolutely, one element can seem to disappear because it’s completely covered by another. The z-index attribute is a good way to check for this situation.
  • Negative z-index can be problematic. The value for z-index should be positive. Although negative values are supported, some browsers (notably older versions of Firefox) don’t handle them well and may cause your element to disappear.
  • It may be best to give all values a z-index. If you define the z-index for some elements and leave the z-index undefined for others, you have no guarantee exactly what will happen. If in doubt, just give every value its own z-index, and you’ll know exactly what should overlap what.
  • Don’t give two elements the same z-index. The point of the z-index is to clearly define which element should appear closer. Don’t defeat this purpose by assigning the same z-index value to two different elements on the same page.

About This Article

This article is from the book:

About the book author:

Nikhil Abraham is the CFO of Udacity, an education company that teaches technology skills that help launch or advance a career. Prior to joining Udacity, Nik worked at Codecademy where he taught beginning coders across a variety of professions. He is also author of Coding For Dummies and Getting a Coding Job For Dummies.

This article can be found in the category: