WHAT IS CSS Z-INDEX PROPERTY? AND HOW DOES IT WORK?

WHAT IS CSS Z-INDEX PROPERTY? AND HOW DOES IT WORK?

·

3 min read

Whenever we need to stack an element on top of another in CSS, we can do so using a property called the z-index. The z-index specifies the order in which these elements are overlapped.

The value of the z-index property is an integer, the element with a higher number places on top of the elements with lower numbers as we see in the boxes below. Thus, the gold box appears first and is placed on top of the stack, the light-green box is second and the blue box comes last.

tempsnip.png

It’s important to note that Z-index works only on positioned elements i.e elements with position: absolute |relative | fixed | sticky. Basically any value other than static.

tempsnip1.png

By default, without z-index, if some elements on our page were to overlap they will do so in the order they appear in our HTML code i.e elements lower down appear on top of the stack. Z-index allows us to control the order of this stacking. An element can also have a z-index of auto, this gives it the same stacking order as it’s parent element.

tempsnip2.png

The gold box is now the last in the stack because its parent element is the body tag as shown below.

     <body>
         <div class="gold-box"></div>
         <div class="green-box"></div>
         <div class="blue-box"></div>
      </body>

Also the z-index of a child element is not compared to elements outside it’s parent. For example if an element J has a higher z-index than element K , a child of J regardless of it’s own z-index will always appear above element K.