Z Index
CSS .z-index property determines the stacking level of positioned overlapping elements. Think of it as the “z-depth” of your web page (toward your direction).
The z-index is a CSS positioning property that defines the order of “nested” elements on the z-axis in the world of web design. It implies which element would be seen more “closer”. Moreover, it requires the element‘s position property to be defined (as none of the other value (constants) would affect the z-index), this is the relative, the absolute or the fixed position. The higher the value, the nearer:
1. The Core Concept
HTML elements normally exist on the page in z-index order, with elements lower down overriding elements higher up, unless you specify otherwise.
- Higher values move elements closer to the viewer (top).
- Lower/Negative values move elements further away (bottom).
2. The Golden Rule: Position
The property z-index will only work on elements that have a position other than by default (static). The only way z-index will work is if you set the property to:
relativeabsolutefixedsticky
Note: It also works on flex items or grid items, even if they are
position: static.
3. How the Values Work
| Value | Description |
auto | Default. Sets the stack order equal to its parent. |
number | Positive or negative integers (e.g., 1, 100, -5). |
initial | Sets the property to its default value. |
Simple Example
Imagine two boxes. Even if Box 1 comes first in your HTML, you can make it sit on top of Box 2:
CSS
.box-1 {
position: relative;
z-index: 2; /* This stays on top */
background: red;
}
.box-2 {
position: relative;
z-index: 1; /* This stays behind */
background: blue;
margin-top: -20px; /* Force them to overlap */
}
4. Stacking Context (The “Group” Rule)
This is where most people get frustrated. Think of a Stacking Context like a folder.
- If “Folder A” has a
z-indexof 1. - And “Folder B” has a
z-indexof 2. - No matter how high you set the
z-indexof an item inside Folder A, it will never appear above Folder B.
5. Common Pitfalls
- Forgotten Position: You set
z-index: 9999but forgot to setposition: relative. - Parent Limitations: An element is trapped behind another because its parent has a lower
z-indexthan the other element’s parent. - Opacity/Filters: Setting
opacity(less than 1) orfilteron an element can unexpectedly create a new stacking context.
Check out our resources!
- Bootstrap Templates: Explore our Bootstrap Projects section.
- Free E-Books: Download your Free E-Books here.


