- This topic is empty.
-
Topic
-
The
z-indexproperty 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-indexdetermines which one appears in front and which one appears behind.Here’s a basic rundown of how
z-indexworks:- Positioning Context: For
z-indexto have any effect, the element must have a positioning value other thanstatic(e.g.,relative,absolute,fixed, orsticky). - Stacking Order: Elements with higher
z-indexvalues are placed in front of elements with lowerz-indexvalues. For example:css.element1 {
position: absolute;
z-index: 10;
}
.element2 {
position: absolute;
z-index: 5;
}
In this case,
.element1will be in front of.element2because it has a higherz-indexvalue. - Default Value: The default value of
z-indexisauto, which means it will follow the stacking order based on the document flow and thepositionproperty. Anautovalue does not explicitly layer the element above or below others with differentz-indexvalues. - Stacking Context: Each positioned element creates a new stacking context. Elements within the same stacking context are ordered according to their
z-indexvalues, 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-indexvalues 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.box3will be:.box2(highestz-indexof 3).box3(middlez-indexof 2).box1(lowestz-indexof 1)
- Positioning Context: For
- You must be logged in to reply to this topic.