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.


CSS Z-index Quiz

Q1: What does z-index control?

A. Vertical spacing
B. Font layering
C. Stacking order of elements
D. Border thickness

Q2: Which property must be set for z-index to work?

A. margin
B. float
C. position
D. display

Q3: Which z-index value places an element on top?

A. -1
B. 0
C. 10
D. auto

Q4: If two elements have the same z-index, which one appears on top?

A. The one with absolute position
B. The one with more padding
C. The one declared later in HTML
D. The one with a larger height

Q5: What does z-index: -1 do?

A. Makes the element invisible
B. Sends the element behind others
C. Adds opacity
D. Zooms out the element

Q6: Which value is valid for z-index?

A. top
B. float
C. 1000
D. none

Q7: Can z-index work without a position value?

A. Yes
B. No
C. Only in inline elements
D. Only in block elements

Q8: What is the default value of z-index?

A. 0
B. 1
C. 10
D. -1

Q9: Which of the following elements will appear above?

A. z-index: 1
B. z-index: 2
C. z-index: 0
D. z-index: -1

Q10: Which scenario is best for using a high z-index?

A. Padding control
B. Background color change
C. Modal or popup window
D. Font styling

Go Back Top