JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
<img src="http://www.centralpark.com/usr/photos/large/25/beautiful-landscape.jpg"></img>
</div>
CSS
#container{
position: relative;
height: 100px;
width: 100px;
border: 1px solid red;
}
#container img{
position: absolute;
}
JavaScript
$(document).ready(function(){
var w = $('#container img').width();
var h = $('#container img').height();
var newsizes = scaletofit(w, h, 100, 100);
$('#container img').css({ width: newsizes[0], height: newsizes[1]});
if(newsizes[0] < 100){
var left = newsizes[0]/2;
$('#container img').css({ left: '50%', 'margin-left': '-'+left+'px' });
}
if(newsizes[1] < 100){
alert('this');
var top = newsizes[1]/2;
$('#container img').css({ top: '50%', 'margin-top': '-'+top+'px' });
}
function scaletofit(imgw, imgh, contw, conth){
var perc = 0;
if((conth / contw) > (imgh / imgw)){
perc = contw / imgw;
} else {
perc = conth / imgh;
}
return [Math.round(imgw * perc), Math.round(imgh * perc)];
}
});