Managing z-index in Your Code
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 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
<html lang = "en-US">
<meta charset = "UTF-8">
<style type = "text/css">
<p id = "blueBox"></p>
<p id = "blackBox"></p>
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
- 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-indexattribute is a good way to check for this situation.
z-indexcan be problematic. The value for
z-indexshould 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-indexfor some elements and leave the
z-indexundefined 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-indexis to clearly define which element should appear closer. Don’t defeat this purpose by assigning the same
z-indexvalue to two different elements on the same page.