How to overlay one div over another div without using position: absolute?

Dmytro picture Dmytro · Oct 23, 2012 · Viewed 54.3k times · Source

I have two divs with two images:

<div id="div1">    

     <div id="div2">
         <img src="img1" />
    </div> 

    <img src="img2" /> 

</div>

Second one is some smaller than first. How can I put second image on first image without using

#div2{
    position: absolute;
}

I need to get similar result but without using position absolute property;

The main issue is that there are a lot of other elements, in parent div, not only div2.

Answer

Robert Koritnik picture Robert Koritnik · Oct 23, 2012

Negative margins

You can do lots with negative margins. I've created an example with just two images without any divs.

img {
    display: block;
}
.small {
    margin: -202px 0 0 0;
    border: 1px solid #fff;
}
.small.top {
    position: relative;
    margin: 0 0 -202px 0;
}
<img src="http://www.lorempixel.com/300/300">
<img class="small" src="http://www.lorempixel.com/200/200">
And some text
<img class="small top" src="http://www.lorempixel.com/200/200">
<img src="http://www.lorempixel.com/300/300">
And some more text