The z-index property to create an effect of layers.
5 July,2021
Basically, the z-index property is used to create a layer untop of another layer effect. Z-index is used to make some/a element(s) look like it is/are untop or under another. You can specify which element should be under and which one should be untop(i.e, stacking them up).
The z-index property only works on Positioned elements . Meaning you can only apply this property to an element with style position to it. For example :
#container{
position: absolute;
z-index: 1;
}
The z-index property can equally take negative values e.g -1
The z-index property controls the vertical order of elements that overlap.As in , which appears as if it is closer to you. As mentiond earlier it affets only elements with that have position value other than thestatic(which is the default).
Without z-index value elements stack in the order they appear in the DOM(the lowest element at same level appears on top).Elements with non-static positioning i.e given another position value like absolute or relative(default) will always appear on top of elements with default staic positioning
Elements can overlap for a variety of reasons, for instance, realtive positioning has nudged it over something else.
Negaive Margin has pulled the element over another. Absolutely posioned elements overlap each other .All sorts of reasons.
Also note that nesting plays a big role . If an element B sits on top of an element A, a child element of,A can never be higher than element B
.c1 { background: rgb(192, 211, 19); width: 200px; height: 100px; position: relative; z-index: 1; } .c2 { background: red; width: 200px; height: 100px; position: relative; z-index: 2; top: -20px; left: 45px; } .c3 { background: blue; width: 200px; height: 100px; position: relative; z-index: 3; top: -30px; left: 90px; }
The CSS code above will produce the stacked div containersa as so