The "z-index" property in CSS positioning serves the purpose of controlling the stacking order of positioned elements on a webpage. It allows web developers to determine which elements should appear in front of or behind other elements, thereby enabling the creation of layered layouts and visual hierarchy. The z-index property accepts integer values, with higher values representing elements that are positioned closer to the viewer.
When elements overlap in a webpage, the stacking order determines which element appears on top. By default, elements are stacked in the order they appear in the HTML markup, with later elements appearing on top of earlier ones. However, the z-index property allows developers to modify this default behavior and rearrange the stacking order as desired.
To use the z-index property, an element must have a position value other than "static" (which is the default position value). The most commonly used position values are "relative", "absolute", and "fixed". Once an element has a non-static position, the z-index property can be applied to it.
Consider the following example:
html
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
position: relative;
background-color: #f1f1f1;
border: 1px solid #ccc;
}
#box1 {
z-index: 2;
}
#box2 {
z-index: 1;
}
</style>
</head>
<body>
<div class="box" id="box1">Box 1</div>
<div class="box" id="box2">Box 2</div>
</body>
</html>
In this example, we have two boxes positioned relatively. Box 1 has a higher z-index value of 2, while Box 2 has a lower z-index value of 1. As a result, Box 1 will appear on top of Box 2, even though Box 2 appears later in the HTML markup. By adjusting the z-index values, we can change the stacking order and control which box appears in front.
It is important to note that the z-index property only works on elements that have a position value other than "static". Additionally, the z-index property only applies within the stacking context of a parent element. If two elements are not siblings or do not share the same parent, their z-index values will not affect each other.
The "z-index" property in CSS positioning is used to control the stacking order of positioned elements on a webpage. It allows developers to determine which elements appear in front of or behind others, enabling the creation of layered layouts and visual hierarchy.
Other recent questions and answers regarding Examination review:
- When should CSS position be used, and when is it better to use padding or margin for layout adjustments?
- What is the difference between absolute positioning and fixed positioning in CSS?
- How does relative positioning work in CSS? Provide an example.
- What are the four main components of the box model in CSS?

