What is Z-Index ?
Z-Index is the property of CSS which is used to order the elements behind and in front in the form of stack. You can consider this a virtual stack where the higher value of z-index is placed infront and the lower value of z index is placed at the back.
To understand this let us consider the html and css code :-
[codepen_embed height=620 theme_id=3 slug_hash='wnDcv' user='Deep_Singh' default_tab='Result' animations='run'/]
This is just a simple code to create 2 boxes and displaying them.The next step is to overlap these two boxes since HTML works on stack basis which means that the bottom code will be displayed on top, so now updating the code we get :-
[codepen_embed height=620 theme_id=3 slug_hash='ctnjB' user='Deep_Singh' default_tab='Result' animations='run'/]
This is just the normal css code with margins defined, but What if we want DIV1 to be placed above DIV2 ? , here Z-Index property comes into effect. Various attributes of z-index are :-
Value Description
auto The browser determines the stack order of the element (based on its order in the document). This is default number An integer that defines the stack order of the element. Negative values are allowed inherit The value of the zIndex property is inherited from parent element
Now adding the z-index property in the CSS code we get the following output.
[codepen_embed height=620 theme_id=3 slug_hash='vizcB' user='Deep_Singh' default_tab='Result' animations='run'/]
Did it worked ?
The answer is
No
! The reason being that the z-index value is pretty much ignored by the browser unless the elements are positioned. We can use position:relative declaration to both elements. Now if we use the code we will get the following output :-[codepen_embed height=620 theme_id=3 slug_hash='EzLmu' user='Deep_Singh' default_tab='Result' animations='run'/]
Remember : We should use larger values, the reason behind is that we should leave room for more values to add and values between 4 and 5 there is no whole number between it and in future we might need to add more z-index between these 2 div's, that's not that important but in advanced designs it might create a problem.
What z-index cannot do ? (in respect to overlapping)
Let us consider a child element of DIV2, a DIV3 which has the z index greater than DIV1 and DIV2, but since its the child element of DIV2 so it will be overlapped with DIV2 and DIV1 will be on the top. To demonstrate this let us consider an example below :-
[codepen_embed height=620 theme_id=3 slug_hash='dCxfl' user='Deep_Singh' default_tab='Result' animations='run'/]