PthPndr PthPndr - 5 months ago 9
CSS Question

Overlaying images works in Chrome/FF/Edge but not IE

I use the following to overlay two images:
Jsfiddle: https://jsfiddle.net/u6y92hmL/1/

HTML:

<div class="overlay-single">
<img class="top" src=http://lorempixel.com/100/100/>
<img class="bottom" src=https://placehold.it/300x200>
</div>


CSS:

.overlay-single {
position: relative;
text-align: center;
}

.overlay-single .top {
position: absolute;
top: 0;
z-index: 1;
}


In Chrome, FireFox, and Edge it works perfectly with the top image sticking to the top left corner of the bottom image. But in Internet Explorer the top image is left justified.

IS there any way I can get IE to behave the same way?

Answer

According to w3c, when left is auto, the absolutely positioned box will appear exactly where it would have had if it wasn’t positioned, which means IE does it wrong and need a fix

Adding an inner wrapper, make it behave as an inline element (size adjust to content), set it to position relative and you will get the wanted result cross browser.

.overlay-single { 
  text-align:center;
}
.overlay-wrapper { 
  position:relative;
  display: inline-block;
}
.overlay-single .top {
  position:absolute;
  top:0;
  z-index:1;
}
<div class="overlay-single">
  <div class="overlay-wrapper">
    <img class="top" src="http://lorempixel.com/100/100/">
    <img class="bottom" src="https://placehold.it/300x200">
  </div>
</div>

Comments