Skip to main content

Command Palette

Search for a command to run...

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

Updated
3 min read
WHAT IS CSS Z-INDEX PROPERTY? AND HOW DOES IT WORK?

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.

311 views
R

I understood quite well👍🏽

A

Awesome breakdown of the css property, picked up a few things I wasn't aware of before.

I

Thank you so much ✨✨😊

W

Nice read, Iyin. 👍

I

Thank you so much✨✨

I
Isaac5y ago

Nicely written article Iyin.

I

Thanks youuu 😊😊

N

Thanks for this 🙌🏾✨

I

You're welcome ✨✨

S

Well explained, looking forward to more of your articles

I

Thank you so much ✨✨

N

thank you for explaining this

1
I

You're most welcome

E

Beautifully explained iyin Dairo. Thanks for sharing.

1
I

Thank you so much. 😊