- This topic is empty.
-
Topic
-
The
z-index
property in CSS controls the stacking order of elements that overlap each other. When you have multiple elements that are positioned on top of each other,z-index
determines which one appears in front and which one appears behind.Here’s a basic rundown of how
z-index
works:- Positioning Context: For
z-index
to have any effect, the element must have a positioning value other thanstatic
(e.g.,relative
,absolute
,fixed
, orsticky
). - Stacking Order: Elements with higher
z-index
values are placed in front of elements with lowerz-index
values. For example:css.element1 {
position: absolute;
z-index: 10;
}
.element2 {
position: absolute;
z-index: 5;
}
In this case,
.element1
will be in front of.element2
because it has a higherz-index
value. - Default Value: The default value of
z-index
isauto
, which means it will follow the stacking order based on the document flow and theposition
property. Anauto
value does not explicitly layer the element above or below others with differentz-index
values. - Stacking Context: Each positioned element creates a new stacking context. Elements within the same stacking context are ordered according to their
z-index
values, but stacking contexts themselves can be nested. This means that an element in one stacking context can appear in front of or behind elements in another stacking context based on their respectivez-index
values and their own stacking contexts.
Here’s a visual example:
html<div class="container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
css.container {
position: relative;
}.box1, .box2, .box3
{
position: absolute;
width: 100px;
height: 100px;
}
.box1 {
background: red;
z-index: 1;
}
.box2 {
background: blue;
z-index: 3;
}
.box3 {
background: green;
z-index: 2;
}
In this example, the stacking order of
.box1
,.box2
, and.box3
will be:.box2
(highestz-index
of 3).box3
(middlez-index
of 2).box1
(lowestz-index
of 1)
- Positioning Context: For
- You must be logged in to reply to this topic.