The z-index property in CSS controls the stacking order of elements that overlap. Elements with a higher z-index value will appear in front of those with a lower z-index value. The z-index property only works on positioned elements (position: relative, position: absolute, position: fixed, or position: sticky).
Key points
Default Value: The default value for z-index is auto, which means the element will follow the order of the HTML structure.
Higher Values in Front: Elements with higher z-index values are stacked in front of elements with lower values.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
color: white;
font-size: 20px;
text-align: center;
line-height: 100px;
}
.box1 {
background-color: red;
top: 50px;
left: 50px;
z-index: 1;
}
.box2 {
background-color: blue;
top: 80px;
left: 80px;
z-index: 3;
}
.box3 {
background-color: green;
top: 110px;
left: 110px;
z-index: 2;
}
</style>
</head>
<body>
<div class="box box1">1</div>
<div class="box box2">2</div>
<div class="box box3">3</div>
</body>
</html>
Notes:
1. Negative Values: z-index can have negative values, which place elements behind those with a z-index of 0 or higher.
2. Non-Positioned Elements: If an element is not positioned (i.e., position: static), the z-index property does not apply to it.
CSS z-index – Interview Questions
Q 1: What is z-index?
Ans: it controls stacking order of elements.
Q 2: When does z-index work?
Ans: When position is not static.
Q 3: Higher z-index means?
Ans: Element appears on top.
Q 4: Can z-index be negative?
Ans: Yes.
Q 5: Common z-index issue?
Ans: Stacking context conflicts.
CSS z-index – Objective Questions (MCQs)
Q1. Which property controls the vertical stacking order of elements?
Q2. z-index works only on elements with which property?
Q3. Which value appears on the top layer?
Q4. Which value sends an element behind others?
Q5. Which value is the default z-index?