How to Use z-index in CSS: Simple Guide with Examples
Use the
z-index property in CSS to control the stacking order of positioned elements. Higher z-index values appear in front of lower ones, but it only works on elements with a position value other than static.Syntax
The z-index property sets the stack order of an element. It only works on elements with position set to relative, absolute, fixed, or sticky.
- z-index: auto; — Default stacking order.
- z-index: number; — An integer value where higher numbers stack on top.
css
selector {
position: relative; /* or absolute, fixed, sticky */
z-index: 10; /* integer value for stack order */
}Example
This example shows two overlapping boxes. The blue box has a higher z-index and appears on top of the red box.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>z-index Example</title> <style> .box { width: 150px; height: 150px; position: absolute; top: 50px; left: 50px; opacity: 0.8; } .red { background-color: red; z-index: 1; } .blue { background-color: blue; top: 100px; left: 100px; z-index: 5; } </style> </head> <body> <div class="box red"></div> <div class="box blue"></div> </body> </html>
Output
A red square partially overlapped by a blue square on the bottom right, with the blue square clearly on top.
Common Pitfalls
Many beginners forget that z-index only works on positioned elements. If position is static (the default), z-index has no effect.
Also, stacking contexts can be tricky: a child element's z-index is relative to its parent stacking context, not the whole page.
css
/* Wrong: z-index ignored because position is static */ .box { z-index: 10; background-color: yellow; width: 100px; height: 100px; } /* Right: position set to relative to enable z-index */ .box { position: relative; z-index: 10; background-color: yellow; width: 100px; height: 100px; }
Quick Reference
| Property | Description | Notes |
|---|---|---|
| z-index | Controls stack order of positioned elements | Higher number = front |
| position | Must be relative, absolute, fixed, or sticky | Default static disables z-index |
| auto | Default z-index value | Uses natural stacking order |
| negative values | Allowed to place behind | Use carefully to avoid hiding content |
Key Takeaways
Always set position to relative, absolute, fixed, or sticky for z-index to work.
Higher z-index values appear on top of lower ones within the same stacking context.
z-index only affects stacking order among siblings in the same stacking context.
Be aware of stacking contexts created by elements with position and z-index.
Negative z-index values can place elements behind others but may hide them unintentionally.