JSFiddle - React, Tailwind, and code Playground

by powtac

HTML

<div class="box"><img class="magic" src="http://upload.wikimedia.org/wikipedia/commons/8/86/Tachyphonus_rufus_-Asa_Wright_Nature_Centre,_Northern_Range,_Trinidad,_Trinidad_and_Tobago_-pair-8a.jpg" /></div>

<div class="box"><img class="magic" src="http://pixabay.com/static/uploads/photo/2011/10/24/21/42/bach-10224_640.jpg?i" /></div>

CSS

.box {overflow:hidden; width:198px; height:198px; border: 1px solid black; margin:50px;}

JavaScript

$(document).ready(function() {
$(".magic").each(function(){
    var self = $(this);
    var width = self.width();
    var height = self.height();

    if(width > height){
        self.css('height', '198px');
        var ratio = width / height;
        self.css('width', 198 * ratio);
        self.css('margin-left', ((198 - parseInt(self.css('width')))/2));
    }
    else{
        self.css('width', '198px');
        var ratio = height / width;
        self.css('height', 198 * ratio);
        self.css('margin-top', ((198 - parseInt(self.css('height')))/2));
    }
});
});