Set image 100% in Div with Jquery

by Faisal Khan Janjua

HTML

<span>
  <div><img src="https://dummyimage.com/800x400/000/fff" /></div>
  <div><img src="https://dummyimage.com/700x300/000/fff" /></div>
  <div><img src="https://dummyimage.com/400x600/000/fff" /></div>
  <div><img src="https://dummyimage.com/500x500/000/fff" /></div>
</span>

CSS

span{
  width: 1150px;
  display: block;
  margin: 100px auto;
}
div {
  width: 150px;
  height: 100px;
  position: relative;
  display: inline-block;
  border:1px solid #F99;
  margin:0 50px;
}
.landscape {
  position: absolute;
  height: 100%;
  left: 50%;
  opacity:0.5;
}
.portrait {
  top: 50%;
  width: 100%;
  opacity:0.5;
  position: absolute;
}

JavaScript

$(function() {
	$('div').each(function(){
    var $img       = $(this).find('img'),
        $imgHeight = $img.height(),
        $imgWidth  = $img.width();  

    if ($imgWidth > $imgHeight) {
        $img.addClass('landscape').css({
                marginLeft: '-' + $img.width() / 2 + 'px',
            });
    } else {
        $img.addClass('portrait').css({
                marginTop: '-' + $img.height() / 2 + 'px',
            });
    }
  });
});