When we talked about positioning, I mentioned that you can use the z-index iproperty to control the Z axis positioning of elements.

It's very useful when you have multiple elements that overlap each other, and you need to decide which one is visible, as nearer to the user, and which one(s) should be hidden behind it.

This property takes a number (without decimals) and uses that number to calculate which elements appear nearer to the user, in the Z axis.

The higher the z-index value, the more an element is positioned nearer to the user.

When deciding which element should be visible and which one should be positioned behind it, the browser does a calculation on the z-index value.

The default value is auto, a special keyword. Using auto, the Z axis order is determined by the position of the HTML element in the page - the last sibling appears first, as it's defined last.

By default elements have the staticvalue for the positionproperty. In this case, the z-indexproperty does not make any difference - it must be set to absolutex, relative or fixedto work.

Example:


.my-first-div {
  position :absolute;
  top :0;
  left :0;
  width :600px;
  height :600px;
  z-index :10;
  background-color :yellow

} 
.my-second-div {
  position :absolute;
  top :0;
  left :0;
  width :500px;
  height :500px;
  z-index :20;
  background-color :blue;
} 

let's the example using our online text editor for better understanding.

Example

<!DOCTYPE HTML>
<html>
    <head>
      <style>
      .my-first-div {
        position :absolute;
        top :0;
        left :0;
        width :600px;
        height :600px;
        z-index :10;
        background-color :yellow
      
      } 
      .my-second-div {
        position :absolute;
        top :0;
        left :0;
        width :500px;
        height :500px;
        z-index :20;
        background-color :blue;
      } 

      </style>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
      <title>Title of the Document</title>
    </head>
    <body>
      <h3>welcome to Coding Koleji </h3>
      <div class="my-first-div">
        <p>this is first div</p>
      </div>
      <div class="my-second-div">
        <p>this is first div</p>
      </div>
      </body>
  </html>

The element with class my-first-div will be displayed, and behind it my-first-div.

Here we used 10 and 20, but you can use any number. Negative numbers too also.

It's common to pick non-consecutive numbers, so you can position elements in the middle.

If you use consecutive numbers instead, you would need to re-calculate the z-index of each element involved in the positioning.