General Explanation about z-index
In CSS, the property z-index
allows us to specify the arrangement of overlapping elements. It might be interesting to note how this capability can affect the design of web pages, especially when we are working with multiple layers; it can be quite useful for users.
Generally speaking, when multiple elements are placed on the page, each of these elements has a z-index
value that determines its position relative to others. The values assigned to z-index
should always be integers, and typically larger numbers mean higher stacking order.
Using z-index
has a key condition: this property only works if the related element has a positioning context (Positioning); specifically, one of the values absolute
, relative
, fixed
, or sticky
must be applied to it.
In real-world design, correctly setting z-index
can help prevent overlapping issues for elements like modals, pop-ups, or any other layouts that need to be correctly layered.
<style>
.box1 {
position: absolute;
top: 50px;
left: 50px;
z-index: 1;
background-color: red;
width: 100px;
height: 100px;
}
.box2 {
position: absolute;
top: 70px;
left: 70px;
z-index: 2;
background-color: blue;
width: 100px;
height: 100px;
}
</style>
<div class="box1">Box 1</div>
<div class="box2">Box 2</div>
Line-by-line Explanation with Code
.box1
: This class specifies the properties of the first box.position: absolute;
: Absolute positioning defines that the first box can use z-index
to be active.top: 50px;
and left: 50px;
: This sets the box's position from the top and left edges of the containing element.z-index: 1;
: The z-index value for this box indicates that it is lower in stacking order than other boxes.background-color: red;
: The background color of the first box is red..box2
: This class specifies the properties of the second box.z-index: 2;
: The z-index value for this box is higher than the first box, meaning this box will be positioned above it.background-color: blue;
: The background color of the second box is blue.