Position one image on top of another

In many situations you may want to position one image on top of another image. There are many ways to achieve this using HTML and CSS. You can find here some easiest methods from this lesson.

The following HTML-CSS code placing one image on top of another by create a relative div that is placed in the flow of the page. Then place the background image first as relative so that the div knows how big it should be. Next is to place the overlay image as absolutes relative to the upper left of the first image.

Position one image on top of another html

HTML-CSS Source Code

<!Doctype> <html> <head> <style> .fishes { position: relative; top: 0; left: 0; } .fish { position: absolute; top: 60px; left: 80px; } </style> </head> <body> <div style="position: relative; left: 0; top: 0;"> <img src="img/fishes.png" class="fishes"/> <img src="img/fish.png" class="fish"/> </div> </body> </html>

position: relative - In relative position method , you can position the element relative to its normal position. In this case you should use left or right and top or bottom to move the element relative to its container.

position: absolute - When we position an element as Absolute , that element is is completely removed from the document`s normal flow. In Absolute position, the position is set through some combination of left, right, top and bottom properties.

More about.... CSS Position

Next approach is using z-index to put an image on top of another image.

Position one image on top of another CSS

HTML-CSS Source Code

<!Doctype> <html> <head> <style> .fishes { position:absolute; top: 10px; left: 10px; z-index: 1; } .fish { position:absolute; top: 25px; left: 25px; z-index: 2; } </style> </head> <body> <img src="img/fishes.png" class="fishes" > <img src="img/fish.png" class="fish"> </body> </html>


While overlapping CSS elements, when using absolute and relative position, the default behavior is to have the first elements underneath later ones. In these cases we can control layering of positioned elements by using the z-index property . When using the z-index property you can specify which of the boxes appears on top the other one.

More about.... z-index