JSFiddle - React, Tailwind, and code Playground

HTML

<div id='myDiv'>
    <img src='https://assets.chess24.com/assets/ca440e559e995201e2242ece6e466b01/images/chess/themes/pieces/chess24/highlight/green.png' id='myImg' > 
</div>

CSS

#myDiv {
  background:green;
  height:200px;
  margin:100px;
  overflow:visible;
  position:relative;   
  width:200px;
}

#myImg {
  background:red;  
  opacity:0.5;
  position:absolute;
}

JavaScript

var IMG = document.getElementById('myImg');
var DIV = document.getElementById('myDiv');


if(IMG.offsetWidth > DIV.offsetWidth) {
  IMG.style.left = (DIV.offsetWidth - IMG.offsetWidth) / 2 + 'px';
}

else {
  IMG.style.left = (IMG.offsetWidth - DIV.offsetWidth) / 2 + 'px';
}

if(IMG.offsetWidth > DIV.offsetWidth) {
  IMG.style.top= (DIV.offsetHeight - IMG.offsetHeight ) / 2 + 'px';
}

else {
  IMG.style.top= (IMG.offsetHeight - DIV.offsetHeight ) / 2 + 'px';
}