With CSS, it’s quite easy to overlap two div elements over one another. To achieve this task we have to use the z-index property in combination with the position property.
The z-index property defines the stacking order of elements. An element with a higher z-index value covers the element with a lower z-index value. We will take advantage of this concept to create overlapping divs.
The most important thing here to remember is that the z-index only works with positioned elements i.e. an element having its position other than static
.
Here is a complete working example:
Example:
.parent{ position: relative; } .child1{ position: absolute; z-index: 1; width: 300px; height: 150px; background: green; opacity: 0.9; border-radius: 5px; } .child2{ position: absolute; top: 20px; left: 20px; z-index: 2; width: 300px; height: 150px; background: red; opacity: 0.9; border-radius: 5px; }
In the above example, the second div will be over the first div because it has a higher z-index value.
If you want the first div to be on the top of the second div, make its z-index value higher than that of the first one.