Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="mask">
    <img src="http://lorempixel.com/600/500" onload="fixSize(this.parentNode)" />
  </div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
 
.mask {
  width: 300px;
  height: 300px;
  overflow: hidden;
}
 
function fixSize(target) {
  const $parent = $(target);
  const $child = $parent.children();
  const pWidth = parseInt($parent.width(), 10);
  const pHeight = parseInt($parent.height(), 10);
  const cWidth = parseInt($child.width(), 10);
  const cHeight = parseInt($child.height(), 10);
  const nWidth = cWidth*pHeight/cHeight
  const nHeight = cHeight*pWidth/cWidth
  const centerX = (nWidth-pWidth)/2;
  const centerY = (nHeight-pHeight)/2;
  if(cHeight*pWidth/cWidth < pHeight) {
    $child.attr("style", "width: "+cWidth*pHeight/cHeight+"px; height: "+pHeight+"px; margin-left: -"+centerX+"px");
  }
  else {
    $child.attr("style", "width: "+pWidth+"px; height: "+cHeight*pWidth/cWidth+"px; margin-top: -"+centerY+"px");
  }
}
Output

This bin was created anonymously and its free preview time has expired (learn why). — Get a free unrestricted account

Dismiss x
public
Bin info
anonymouspro
0viewers