🤔 What is z-index?

z-index controls the stacking order of elements on a webpage.
It decides which element appears on top when elements overlap.

👉 Higher z-index = comes on top ⬆️

 

⚠️ Important Rule (Interview Must-Know)

👉 z-index works only on positioned elements
That means the element must have a position property other than static.

 

✅ Position Properties That Support z-index

1️⃣ position: relative 📦

.box1 {
  position: relative;
  z-index: 2;
}

✔️ Works with z-index

2️⃣ position: absolute 🎯

.box2 {
  position: absolute;
  z-index: 3;
}

✔️ Commonly used with z-index

3️⃣ position: fixed 📌

.header {
  position: fixed;
  z-index: 100;
}

✔️ Used for sticky headers & menus

4️⃣ position: sticky 🧲

.navbar {
  position: sticky;
  top: 0;
  z-index: 10;
}

✔️ Works when the element becomes sticky

 

❌ Position That Does NOT Work with z-index

🚫 position: static (Default)

.box {
  position: static;
  z-index: 5; /* ❌ Won't work */
}

❌ z-index has no effect here.

 

🧩 Simple Example

<div class="red"></div>
<div class="blue"></div>
.red {
  position: absolute;
  background: red;
  z-index: 1;
}

.blue {
  position: absolute;
  background: blue;
  z-index: 2;
}

🔵 Blue box appears on top because it has a higher z-index.

 

🎯 Interview Answer (Short & Strong)

z-index works only with positioned elements like relative, absolute, fixed, and sticky. It does not work with static position.

 

✅ Key Takeaways

  • z-index controls stacking order 🧱

  • Works with relative, absolute, fixed, sticky

  • Does NOT work with static ❌

 

💡 Pro Tip: Always set position before using z-index 👍