JSFiddle - React, Tailwind, and code Playground
by elvinci
HTML
<div class="box">
<img src="https://i.ytimg.com/vi/Lzx2NrMQHJM/maxresdefault.jpg"/>
</div>
CSS
.box{height:100%;width:100%;overflow:hidden}
.body{
width:100%;
height:100%;
}
.wh{height:100%!important}
.ww{width:100%!important}
JavaScript
$('.box').each(function() {
//set size
var th = $(this).height(),//box height
tw = $(this).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if (ih>iw) {//if portrait
im.addClass('ww').removeClass('wh');//set width 100%
} else {//if landscape
im.addClass('wh').removeClass('ww');//set height 100%
}
//set offset
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (nh<nw) {//if portrait
im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
} else {//if landscape
im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
}
});