CSS Z-index
The z-index
property in CSS is used to control the stacking order of elements on a webpage. It specifies the stack level of an element along the Z-axis, which determines the order in which elements are displayed on top of each other. Elements with a higher z-index
value will appear on top of elements with a lower z-index
value.
Syntax
selector {
z-index: value;
}
The z-index
property accepts an integer value, where a higher value means the element will be positioned closer to the user.
Examples
Let's consider a simple example with two div elements:
<div class="box1"></div>
<div class="box2"></div>
Here is the CSS style for the div elements:
.box1 {
width: 100px;
height: 100px;
background-color: red;
float:left;
z-index: 1;
}
.box2 {
width: 100px;
height: 100px;
background-color: blue;
float:left;
margin-left:-30px;
margin-top:10px;
z-index: 2;
}
In this example, the blue box (box2) will appear on top of the red box (box1) because it has a higher z-index
value.
Important Points
- Elements with a higher
z-index
value will appear on top of elements with a lowerz-index
value. - When elements overlap, the
z-index
value determines which element appears on top.