CSS Z-index


🔹 What is z-index in CSS?

The z-index property in CSS specifies the stacking order of elements along the z-axis (i.e., which element appears in front of or behind another).

It only works on positioned elements (relative, absolute, fixed, or sticky).


🔸 Syntax

element {
  position: relative;
  z-index: 2;
}

✅ A higher z-index means the element will be placed on top of others with a lower z-index.


🔸 Key Points

  • Default z-index is auto (treated as 0).

  • Only works when the element is positioned (not static).

  • Elements with higher z-index appear in front.

  • If two elements have the same z-index, the later one in HTML appears on top.


🔸 Example

.box1 {
  position: absolute;
  z-index: 1;
  background-color: red;
}

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

.box2 will appear on top of .box1.


🔸 Negative z-index

.box {
  position: relative;
  z-index: -1;
}

✅ Element is placed behind others (often even behind the background).


🔸 Common Use Cases

  • Layering modal windows

  • Placing tooltips above elements

  • Arranging background and content layers

  • Creating image stacks or cards


Practice Questions

Q1. Make a div appear above another using z-index.

Q2. Stack .card1, .card2, and .card3 with increasing z-index.

Q3. Place a modal dialog above all other elements.

Q4. Hide an element behind the background using z-index: -1.

Q5. Create overlapping boxes and control their layer order.

Q6. Write a rule where a tooltip appears above a button.

Q7. Use inline CSS to set z-index: 9999 on a <div>.

Q8. Set multiple elements with the same z-index and observe stacking.

Q9. Create a notification banner that always appears on top.

Q10. Write a positioned container and a child with a higher z-index.


Go Back Top