JSFiddle - React, Tailwind, and code Playground
HTML
test image ratio w/h = 4
<div>
<img id="myimg" src='http://placehold.it/200x50' draggable="false"/>
</div>
<br/>
test image ratio w/h = 0.25
<div>
<img id="myimg" src='http://placehold.it/50x200' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 but small
<div>
<img id="myimg" src='http://placehold.it/50x50' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 perfect fit
<div>
<img id="myimg" src='http://placehold.it/300x300' draggable="false"/>
</div>
<br/>
test image ratio w/h = 1 much too big
<div>
<img id="myimg" src='http://placehold.it/2000x2000' draggable="false"/>
</div>
CSS
.bev {
border: solid 1px green;
width: 300px;
height: 300px;
overflow: hidden;
border-radius: 10px;
margin-left: 10px;
}
div img {
outline: solid 1px red;
}
.fillwidth {
width: 100%;
max-height: 99999px;
position: relative;
/*top*/
}
.fillheight {
height: 100%;
max-width: 99999px;
position: relative;
/*left*/
}
.fillfull {
height: 300px;
width: 300px;
}
JavaScript
$('img[id^="myimg"]').each(function() {
var imgWidth = $(this).width(),
imgHeight = $(this).height(),
imgRatio = imgWidth / imgHeight,
imgWidthTop = (((300 / imgWidth) * imgHeight) / 2) * -1 + 300 / 2,
imgHeightLeft = (((300 / imgHeight) * imgWidth) / 2) * -1 + 300 / 2;
//alert(imgRatio);
switch rue) {
case (imgRatio < 1.1 && imgRatio > .99):
$(this).addClass('fillfull');
break;
case (imgRatio < 1):
$(this).addClass('fillwidth');
$(this).css('top', imgWidthTop);
//$(this).css('clip', 'rect(100px 0 100px 0)');
$(this).parent().addClass('bev');
break;
case (imgRatio > 1):
//$(this).css('clip', 'rect(0 100px 0 100px)');
$(this).addClass('fillheight');
$(this).css('left', imgHeightLeft);
$(this).parent().addClass('bev');
break;
default:
break;
}
});