Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / CSS3

Z-Index in CSS with Example

5.00/5 (1 vote)
4 Apr 2013CPOL1 min read 34.6K   178  
Z-Index a CSS property with example

Introduction

This tip helps to understand CSS property "Z-Index".

Background

Many people are confused with how actually the elements in HTML are arranged. Also, some people may not be use this property. Z-Index is an important property of CSS. So I thought of writing a tip on the same. Hope this will help someone.

Using the Code

So far, you know x-axis and y-axis and what actually they refer to. Likewise, there is another axis which shows the order of elements called Z-Axis. It is also called as Z_Index in CSS, which means ordering of elements in stack order.

Stack: A stack is a basic data structure, where insertion and deletion of items takes place at one end called the top of the stack.

Example: Arranging 10 plates one above the other, where you can only take the plate which is at the top and you put another plate at the top itself.

The above example shows that the plate which is at the bottom has less Z-Index and plate that is at the top has higher Z-Index.

The below image shows three divisions ordering each other with different Z-Index values.

The following source code will help you understand about Z-Index through code.

CSS
<style type="text/css">
      .div_exp1
      {
          border: solid 1px silver;
          background-color: #f2f2f2;
          position: absolute;
          z-index: 100;
          height: 100px;
          width: 100px;
      }
      .div_exp2
      {
          border: solid 1px silver;
          top: 30px;
          left: 30px;
          background-color: #c2c2c2;
          position: absolute;
          z-index: 101;
          height: 100px;
          width: 100px;
      }
      .div_exp3
      {
          border: solid 1px silver;
          top: 60px;
          left: 60px;
          background-color: #565656;
          position: absolute;
          z-index: 102;
          height: 100px;
          width: 100px;
      }
  </style>
HTML
<div>
       <div class="div_exp1" id="div1">
           Z-Index 100
       </div>
       <div class="div_exp2" id="div2">
           Z-Index 101
       </div>
       <div class="div_exp3" id="div3">
           Z-Index 102
       </div>
   </div>

Points of Interest

Initially, I was confused as to how elements are placed one above the other. But later, I came to know what actually happens. Hope this tip will be very interesting to all.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)