Search code examples
htmlcssoverlapoverlapping

CSS: Overlaping two images and proper flow


As you can see in http://jsfiddle.net/omarjuvera/v93us4n9/6/ the paragraph is not where it should be, since I am overlapping two images. How can I fix this?

HTML

<h1>Overlaping two images</h1>
<div>
    <img src="http://img.youtube.com/vi/brMyE7To7Sg/0.jpg" />
    <img src="http://oi57.tinypic.com/2u8kr2s.jpg" />
</div>
<br/>

<p>For some reason, this paragraph is not below DIV, but under/over</p>

CSS

div {
    position: relative;
}
img {
    position: absolute;
    left: 0px;
    top: 0px;
}

Solution

  • It's because both of the img elements are absolutely positioned and removed from the flow.

    Due to this, the parent div element collapses upon itself and has a height of 0. Unless the parent div element has explicit dimensions, in this case a height, the text will overlap.

    Setting an explicit height on the parent element will solve this, but that's not a very flexible solution.

    In your case, since the img elements are the same size, you could solve this by only absolutely positioning a single img element. In doing so, the height of the parent div element will be defined based on the height of the img element that isn't absolutely positioned.

    Updated Example

    <div>
        <img src="//placehold.it/480x360" />
        <img class="overlay" src="http://oi57.tinypic.com/2u8kr2s.jpg" />
    </div>
    
    div {
        position: relative;
    }
    img.overlay {
        position: absolute;
        left: 0px;
        top: 0px;
    }