JSFiddle - React, Tailwind, and code Playground
HTML
<img id="bg" src="https://www.google.com/images/srpr/logo11w.png" />
CSS
body {
background: black;
overflow: hidden;
}
img {
position: relative;
}
.bgwidth {
width: 50%;
}
.bgheight {
height: 100%;
left: 50%;
}
JavaScript
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
var imgWidth = $bg.width();
var imgHeight = $bg.height();
function resizeBg() {
var heightDifference = (theWindow.height() - $bg.height()) / 2;
if ((theWindow.width() / theWindow.height()) < aspectRatio) {
$bg.removeClass().addClass('bgheight');
$bg.css("margin", heightDifference + "px 0 0 -" + imgWidth / 2 + "px");
} else {
$bg.removeClass().addClass('bgwidth');
$bg.css("margin", heightDifference + "px 0 0 0");
}
}
theWindow.resize(resizeBg).trigger("resize");