- Home
- /
- Tutorials
- /
- CSS Tutorial
- /
- CSS Z-index
CSS Layout
CSS Z-index
The CSS Z-index property controls the stacking order of positioned elements on a webpage.
When two or more elements overlap, the element with the higher z-index value appears in front of the others.
Think of z-index as layers stacked on top of each other:
- Higher z-index = Closer to the user
- Lower z-index = Further behind
Z-index is commonly used for:
- Navigation menus
- Popups and modals
- Tooltips
- Dropdown menus
- Floating buttons
Syntax
CSS Z-index Syntax
css
selector {
z-index: value;
}CSS Z-index Example
css
.box {
position: absolute;
z-index: 10;
}This places the element above elements with lower z-index values.
Attributes
| Property | Description | Example |
|---|---|---|
| z-index | Sets stacking order | z-index: 5; |
| z-index | Higher value appears in front | z-index: 100; |
| z-index | Lower value appears behind | z-index: 1; |
| z-index | Negative stacking order | z-index: -1; |
| z-index | Default stacking order | z-index: auto; |
Example
CSS Z-index Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>CSS Z-index Example</title>
<style>
.container {
position: relative;
height: 250px;
}
.box1 {
position: absolute;
top: 20px;
left: 20px;
width: 200px;
height: 150px;
background-color: lightblue;
z-index: 1;
}
.box2 {
position: absolute;
top: 60px;
left: 80px;
width: 200px;
height: 150px;
background-color: orange;
z-index: 2;
}
</style>
</head>
<body>
<div class="container">
<div class="box1">Box 1 (z-index: 1)</div>
<div class="box2">Box 2 (z-index: 2)</div>
</div>
</body>
</html>Output
Browser Output
css
Two boxes will overlap
The orange box (z-index: 2) will appear in front
The blue box (z-index: 1) will appear behind
The higher z-index value determines which element is visible on topBrowser Support
Chrome | Edge | Firefox | Safari | Opera | IE |
|---|---|---|---|---|---|
| Yes | Yes | Yes | Yes | Yes | Yes |
Notes
z-indexonly works on positioned elements:position: relative,position: absolute,position: fixed, andposition: sticky.- Elements with higher
z-indexvalues appear above lower values. - Negative
z-indexvalues can place elements behind others. z-index: autouses the default stacking order.- Avoid extremely large
z-indexvalues unless necessary.
Common Layering Example
| Element | Typical Z-index |
|---|---|
| Page Content | 1 |
| Sticky Header | 100 |
| Dropdown Menu | 1000 |
| Modal Window | 10000 |
| Tooltip | 100000 |
Conclusion
The CSS Z-index property is essential for controlling the stacking order of overlapping elements. By using z-index with positioned elements, you can create dropdowns, modals, tooltips, and other layered interface components that appear correctly above or below other content.
