How to Make the CSS z-index Property Work

Solutions with the CSS position property

The CSS z-index property only works with the position property. The position value must be other than static (i.e. absolute, relative, fixed, sticky).

Let’s see some examples.

For regular positioning, use the "relative" value on the elements, on which you’ve also set the z-index property. Otherwise, there won’t be any effect.

Example of using the z-index property with the "relative" value of the position property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        width: 150px;
        height: 150px;
        padding: 15px;
      }
      .one,
      .two,
      .three {
        position: relative;
      }
      .one {
        background: #a7b5aa;
        outline: 2px solid #000;
        top: 100px;
        left: 200px;
        z-index: 10;
      }
      .two {
        background: #4b48db;
        outline: 2px solid #000;
        top: 50px;
        left: 75px;
        z-index: 100;
      }
      .three {
        background: #1ba13f;
        outline: 2px solid #000;
        top: 30px;
        left: 25px;
        z-index: 150;
      }
    </style>
  </head>
  <body>
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
  </body>
</html>

Result

Example of using the z-index property with the "absolute" value of the position property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img {
        position: absolute;
        left: 0;
        top: 20px;
        z-index: -1;
      }
    </style>
  </head>
  <body>
    <h2>Example</h2>
    <img src="/build/images/w3docs-logo-black.png" alt="W3docs logo" width="195" height="45">
  </body>
</html>

Now, let’s see how these boxes will behave with the "fixed" value.

Example of using the z-index property with the "fixed" value of the position property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        width: 150px;
        height: 150px;
        padding: 15px;
      }
      .one,
      .two,
      .three {
        position: fixed;
      }
      .one {
        background: #a7b5aa;
        outline: 2px solid #000;
        top: 100px;
        left: 200px;
        z-index: 10;
      }
      .two {
        background: #4b48db;
        outline: 2px solid #000;
        top: 50px;
        left: 75px;
        z-index: 100;
      }
      .three {
        background: #1ba13f;
        outline: 2px solid #000;
        top: 30px;
        left: 25px;
        z-index: 150;
      }
    </style>
  </head>
  <body>
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
  </body>
</html>

When the z-index property is not applied, the browser stacks elements in the following default order:

  1. root element,
  2. non-positioned elements in the order they are specified,
  3. positioned elements in the order they are specified.