Elements positioned on a webpage may overlap each other. The z-index
property controls the stacking order of elements, determining which element appears in front of or behind others. This order can be adjusted to either raise or lower an element relative to its counterparts.
img {
position: relative;
display: block;
z-index: -1;
}
h1 {
position: absolute;
left: 0;
top: 0;
}
In this code, the negative z-index
of -1
is applied to the image, which will position it behind the text content on the page, as you can see in the below preview.
Note: The z-index
property is effective only on elements that have a defined position such as position: absolute
, position: relative
, position: fixed
, or position: sticky
. Additionally, it applies to flex items, which are direct children of elements with display: flex
.
Another z-index Example
.parent {
position: relative;
background-color: lightgray;
}
.box1 {
position: absolute;
top: 10px;
left: 10px;
background-color: tomato;
z-index: 1;
}
.box2 {
position: absolute;
top: 50px;
left: 50px;
background-color: deepskyblue;
z-index: 3;
}
.box3 {
position: absolute;
top: 90px;
left: 90px;
background-color: lawngreen;
z-index: 2;
}
In this example:
.box1
has the lowestz-index
of1
, so it will be behind both.box2
and.box3
..box2
has the highestz-index
of3
, so it will be displayed on top of both.box1
and.box3
..box3
has az-index
of2
, placing it on top of.box1
but behind.box2
.
This demonstrates how the z-index
property controls the stacking order of positioned elements within a relatively positioned container (<div>
with class .parent
).
Without z-index
When two positioned elements overlap each other and no z-index
is set, the element that appears later in the HTML code will be displayed on top. This is because HTML elements are rendered sequentially, and CSS styling applies in a cascading manner, prioritizing elements defined later in the document for overlapping display.
.parent {
position: relative;
background-color: #f0f0f0;
}
.box1 {
position: absolute;
top: 10px;
left: 10px;
background-color: #ff6347;
}
.box2 {
position: absolute;
top: 50px;
left: 50px;
background-color: #00bfff;
}
.box3 {
position: absolute;
top: 90px;
left: 90px;
background-color: #7cfc00;
}
In this example, due to the stacking order in HTML/CSS (where elements later in the HTML code appear on top of earlier ones if they overlap), the visual display will show:
.box1
behind both.box2
and.box3
..box2
on top of.box1
but behind.box3
..box3
on top of both.box1
and.box2
.
Please check below options for the links to our previous or next tutorial.