In many situations when we are working with images, we might need to place one image on top of the other. In this article, we will learn an easy method that can be used to overlap images using simple HTML & CSS.
See the below overlapping images:
To overlap images in CSS, we can use the position and the z-index property in a combination. Simply put the images that you want to overlap inside a <div>
element, and set its position to relative
.
Now, set the position of each image to absolute
, so that we can control its positioning using the top, left, bottom, and right properties.
In case you don’t know, an absolutely positioned element is positioned relative to its nearest positioned ancestor. This is the reason, we set the <div>
element position to relative
.
Now, to define the stacking order of the images, you have to set a z-index for each image.
Here is a fully working example of it:
Example:
/* Image Container */ .container{ position: relative; width: 300px; height: 300px; } .img1{ position: absolute; z-index: 1; width: 100%; top: 0; left: 0; } .img2{ position: absolute; z-index: 2; /* Place this image in front of the img1 */ width: 100%; top: 100px; left: 100px; }
Overlap Multiple Images
With the method that we discussed in the above example, we can overlap any number of images on one another.
In the below example we are overlapping 3 images on top of each other. The basic concept is the same as the above.
The only thing that we have changed here is the z-index, which we have set to 3 for the third image which is 1 more than that of the second one.
See the below overlapping images:
Here is a working example:
Example:
/* Image Container */ .container{ position: relative; width: 300px; height: 300px; } .img1{ position: absolute; z-index: 1; width: 100%; top: 0; left: 0; } .img2{ position: absolute; z-index: 2; /* Place this image in front of the img1 */ width: 100%; top: 50px; left: 50px; } .img3{ position: absolute; z-index: 3; /* Place this image in front of the img2 */ width: 100%; top: 100px; left: 100px; }