CSS z-index
Note: This property is only applicable to the positioned element, which means that the position of the element should not be static.
So, what does this property determine? It determines the stack level of the element in the stacking context. This means that if the elements are positioned, it may happen that they are arranged in a stack. If such a thing happens, then which element should get first priority to be on the top of the stack of those elements?
This is determined by the property z-index. So, the greater the value of the z-index, the higher the priority of the element to be on the top. If you want one element to be on the top of the other, then simply put a greater z-index value to that element that you wish should be on the top.
If you are not getting the concept, don’t worry, we are going to have an example, which would make things clear. The example is quite abstract, but it would help us understand the concept in a simple way.
Now, consider that we have 3 different divs, with some ids. Let’s say that they are positioned, which means that their position is not static. Here is the code for the same –
In the below code, you can see that the three divs are positioned. Here is what it looks like –
Basically, they are appearing somewhat on top of each other. The pink color div appears to be on the top of the green color one, and the dark turquoise color div appears to be on the top of the pink one. So, we can consider that they are somewhat stacking up. Now, we have control over who should be on the top. Just by adjusting the value of the z-index property, we can determine who should be on the top of that stack.
Simply, whatever element we want on top of the stack, we should put the value of the z-index property as the highest. Read that line again. Now, let’s have an example, with the z-index values set for these divs. Now, let’s consider that we want the pink div to be on the top. So, the value of the z-index property for the pink color div is supposed to be the highest.
So, we have set the z-index for the elements. Here is just the CSS, since we have only changed that –
As a result, you can see that the pink div is now on the top. Have a look at the output –
So, you can simply understand the z-index property with the help of the above examples. You can try some other examples as well, and try playing with the property.