CSS Z-index

The z-index property in CSS is used to control the stack order of elements that overlap each other. Elements with a higher z-index cover those with a lower index.


How z-index Works

Example
Try yourself
        
            div {
  width: 100px;
  height: 100px;
  position: absolute;
}
.red-box {
  background-color: red;
  left: 20px;
  top: 20px;
  z-index: 2;
}
.blue-box {
  background-color: blue;
  left: 50px;
  top: 50px;
  z-index: 1;
}
        
    

In this example, the red box has a higher z-index and will cover part of the blue box.


Overlapping without z-index

If z-index is not set, elements are stacked in the order they appear in the HTML:

Try yourself
        
            div {
  width: 100px;
  height: 100px;
  position: absolute;
}
.red-box {
  background-color: red;
  left: 20px;
  top: 20px;
}
.blue-box {
  background-color: blue;
  left: 50px;
  top: 50px;
}
        
    

Using Negative z-index

You can also use negative values for z-index to place elements behind others:

Try yourself
        
            .container {
  position: relative;
}
.background {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: yellow;
  z-index: -1;  /* Behind the content */
}
.content {
  position: relative;
  z-index: 1;  /* Above the background */
}
        
    

Complex Stacking Contexts

When multiple elements interact with various z-index values, their relationships can become complex. For instance:

Try yourself
        
            .outer {
  position: relative;
  z-index: 1;
  width:200px;
  background-color: red;
  height:200px;
}
.inner {
  position: absolute;
  z-index: 5;
}
.background {
  position: absolute;
  z-index: 2;
  background-color: green;
  width: 100px;
  height: 100px;
}
        
    

Conclusion

Understanding z-index is essential for managing the layout of overlapping elements on web pages. Experimenting with different values and positions can help you better understand how stacking contexts are formed and interact.