Managing z-index in Your Code

By Nikhil Abraham

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.

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:

<!DOCTYPE html>

<html lang = "en-US">



<meta charset = "UTF-8">


<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;





<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 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.