html
/

CSS Z-Index

Last Sync: Today

On this page

12
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

CSS Z-Index

What is Z-Index?

The z-index property controls the vertical stacking order of positioned elements (which element appears on top).

Basic Example

CSSRead-only
1
.box1 {
  position: absolute;
  z-index: 1;
}

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

Higher Value = On Top

Elements with higher z-index values appear above elements with lower values.

Position Requirement

z-index works only on positioned elements (position: relative, absolute, fixed, sticky).

CSSRead-only
1
div {
  position: relative;
  z-index: 10;
}

Default Stacking

Without z-index, elements stack based on their order in the HTML (later elements appear on top).

Negative Z-Index

CSSRead-only
1
div {
  position: relative;
  z-index: -1;
}

Stacking Context

A stacking context is formed when an element has a position and z-index, isolating its children from other elements.

Example

CSSRead-only
1
.parent {
  position: relative;
  z-index: 1;
}

.child {
  position: absolute;
  z-index: 999;
}

Common Use Cases

  • Modals and popups
  • Dropdown menus
  • Tooltips
  • Fixed headers and overlays

Best Practices

  • Use minimal z-index values
  • Maintain a z-index scale (e.g., 1–10–100)
  • Avoid excessive stacking levels
  • Understand stacking context before debugging

Common Mistakes

  • Using z-index without position
  • Confusion due to stacking context
  • Overusing large values (9999)
  • Unexpected overlap issues

Conclusion

CSS z-index controls element layering. Understanding positioning and stacking context is key to mastering it.

Try it yourself

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

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

Test Your Knowledge

Q1
of 3

Which appears on top?

A
Lower z-index
B
Higher z-index
C
Equal z-index
D
None
Q2
of 3

z-index works with?

A
display
B
position
C
color
D
margin
Q3
of 3

Default stacking depends on?

A
z-index
B
HTML order
C
CSS order
D
position

Frequently Asked Questions

Why is z-index not working?

Because position is not set.

What is stacking context?

A layer grouping that controls child stacking.

Can z-index be negative?

Yes, to place elements behind others.

Previous

css overflow

Next

css flexbox

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.