Handling depth in CSS
You can use a special CSS attribute calledz-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.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:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>zindex.html</title>
<style type = "text/css">
#blueBox {
background-color: blue;
width: 100px;
height: 100px;
position: absolute;
left: 0px;
top: 0px;
margin: 0px;
z-index: 1;
}
#blackBox {
background-color: black;
width: 100px;
height: 100px;
position: absolute;
left: 50px;
top: 50px;
margin: 0px;
}
</style>
</head>
<body>
<p id = "blueBox"></p>
<p id = "blackBox"></p>
</body>
</html>
Working with z-index
The only change in this code is the addition of thez-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 forz-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 thez-index
for some elements and leave thez-index
undefined for others, you have no guarantee exactly what will happen. If in doubt, just give every value its ownz-index
, and you’ll know exactly what should overlap what. - Don’t give two elements the same
z-index
. The point of thez-index
is to clearly define which element should appear closer. Don’t defeat this purpose by assigning the samez-index
value to two different elements on the same page.