z-index is a CSS property that controls stacking order of elements along Z axis.
The z-index property in CSS controls the vertical stacking order of elements that overlap. z-index only affects on positioned elements.
Specification of position (relative, absolute, sticky, fixed) if you want to arrange an element using z-index,
Without any z-index value, elements stack in the order that they appear in the DOM (the lowest one down at the same hierarchy level appears on top).
Elements with non-static positioning (and their children) will always appear on top of elements with default static positioning, regardless of HTML hierarchy.
A stacking context is an element that contains a set of layers. Within a local stacking context, the z-index values of its children are set relative to that element rather than to the document root.
Layers outside of that context — i.e. sibling elements of a local stacking context — can't sit between layers within it.
Let's say two elements A and B are siblings with element B written after element A in DOM, then the children of element A cannot be higher than element B no matter what z-index is being applied on children.
z-index: 1;
z-index: 100;
z-index: 2;
Element A with z-index as 1.
Child of Element A with z-index as 100.
Element B with z-index as 2.
Each stacking context is self-contained - after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.
A handful of CSS properties trigger a new stacking context, such as opacity less than 1, filter that is not none, and transform that is not none.
Code:
Link 1:
https://stackblitz.com/edit/js-nm98dv?file=index.html
Link 2: for better understanding.
https://stackblitz.com/edit/js-vbnhrb?file=index.html