CSS Z-Index Property
The CSS z-index property controls the stacking order of elements that overlap. Think of it as determining which element is “on top” when elements occupy the same space on the webpage.
Important Note: z-index only works on elements that have a position value other than static (i.e., relative, absolute, fixed, or sticky). For statically positioned elements, the stacking order is determined by their order in the HTML.
Purpose:
To control which overlapping element appears in front of or behind others.
To manage the visual layering of elements on a webpage.
Syntax
element {
position: relative; /* Or absolute, fixed, sticky */
z-index: value;
}
element: The HTML element whose stacking order you want to control.
position: relative; (or other non-static values): This is crucial for z-index to have an effect.
value: An integer value (can be positive, negative, or zero).
- Elements with a higher z-index value will be stacked in front of elements with lower z-index values.
- Elements with the same z-index value are stacked according to their order in the HTML source code (later elements appear on top).
- Negative z-index values can push elements behind their non-positioned parent.
Example:
<!DOCTYPE html>
<html>
<head>
<title>CSS z-index Example</title>
<style>
.box {
width: 150px;
height: 100px;
position: absolute;
}
.box1 {
background-color: lightblue;
left: 20px;
top: 20px;
z-index: 1;
}
.box2 {
background-color: lightcoral;
left: 50px;
top: 50px;
z-index: 2; /* Higher z-index, so it's on top */
}
.box3 {
background-color: lightgreen;
left: 80px;
top: 80px;
z-index: -1; /* Lower z-index, potentially behind the parent */
}
.container {
position: relative; /* Establishes a stacking context */
width: 200px;
height: 150px;
border: 1px solid black;
margin: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="box box1">Box 1 (z-index: 1)</div>
<div class="box box2">Box 2 (z-index: 2)</div>
<div class="box box3">Box 3 (z-index: -1)</div>
</div>
</body>
</html>
Explanation:
HTML Structure:
- We have a .container div that is positioned relative. This establishes a stacking context for its absolutely positioned children.
- Inside the container, we have three div elements (.box1, .box2, .box3) that are positioned absolute.
CSS Styling:
- .box: Sets basic dimensions and makes the boxes absolutely positioned.
- .box1: Has a z-index of 1.
- .box2: Has a z-index of 2. Because its z-index is higher than .box1, it will appear on top.
- .box3: Has a z-index of -1. This will likely place it behind the .container div (since the container has a default z-index of auto, which behaves like 0 in this context).
- .container: Is positioned relative, making it a stacking context for its absolute children.