JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
</head>
<body>
<div class="background"></div>
</body>
</html>
CSS
div.background {
background: url('http://media.npr.org/assets/img/2012/02/24/111926395-google-logo-sun_wide-0d0561b99d3ab663b53af249bf6bce1627240104-s6-c10.jpg') no-repeat;
background-size:contain;
background-position:center;
width:100%;
height:500px;
float:left;
}
JavaScript
var calculate_positions = {
img_width:948,
img_height:532,
img_ratio:function(){
return calculate_positions.img_width / calculate_positions.img_height;
},
elm_ratio:function(elm){
return $(elm).width() / $(elm).height();
},
img_offset:function(elm){
var offset = []; //[x,y]
if(calculate_positions.elm_ratio(elm) > calculate_positions.img_ratio()){
//centered x height 100%
var scale_percent = $(elm).height() / calculate_positions.img_height;
var scaled_width = calculate_positions.img_width * scale_percent;
var x_offset = ($(elm).width() - scaled_width) / 2;
offset = [x_offset, 0];
}else{
//centered y width 100%
var scale_percent = $(elm).width() / calculate_positions.img_width;
var scaled_height = calculate_positions.img_height * scale_percent;
var y_offset = ($(elm).height() - scaled_height) / 2;
offset = [0, y_offset];
}
return offset;
}
}
$(window).resize(function(){
var offset = calculate_positions.img_offset($('div.background'));
console.log(offset);
})