The z-index property has caused a lot of confusion more than any other CSS property. It’s not complicated, the problem is that a few people understand how it really works. z-index is not a difficult property to understand. But due to false assumptions and incomplete knowledge, it causes confusion.
Eventually, it seems very simple involving elements with higher z-index stacked in front of the elements with lower z-index. Well, this is not all. It appears this simple, and so most of us do not understand the whole concept deeply.
Let us have an insight into the property.
The z-index property determines the stacking order of HTML elements.
What does the term 'stacking order' mean?
Every element in an HTML document can be placed either in front of the other element or behind an element in the document. This is called the stacking order. The 'stack level' or 'stacking order' refers to the position of the element on the Z axis. Element with a larger z-index will be closer to the top in the stacking order.
We are all familiar with three-dimensional coordinate space. It has an x-axis, used to represent the horizontal direction, a y-axis to represent the vertical direction, and a z-axis used to represent anything that comes in or goes out of the page. z-index helps us determine which is inside and which is outside (of the screen, in our case) and in what order.
To determine where along the Z-axis an HTML element is located, we set 3 values on z-index property :
auto (by default)
The integer value can be positive, negative, or 0. The greater the value, the closer the element appears and vice-versa.
The syntax is as follows :
z-index only works on elements whose position has been specified. That is, ones whose position property has been explicitly set to : absolute, fixed, or relative. It means the value should be other than static (by default).
The following example will give you a clearer picture.