JSFiddle - React, Tailwind, and code Playground
HTML
<div class="horizontal">
<img src="http://lh5.ggpht.com/5tPSImy2l8oXzocjPpiHXRnW0Q1iN9mLO4XpDTKVacaXzqybsVW17akzuP9tG0l7G1VNHHVDhDPx-jhsHxgAkLtG5SiOwAa_yAv8SJiu=s250" alt="" />
</div>
<div class="vertical">
<img src="http://lh5.ggpht.com/5tPSImy2l8oXzocjPpiHXRnW0Q1iN9mLO4XpDTKVacaXzqybsVW17akzuP9tG0l7G1VNHHVDhDPx-jhsHxgAkLtG5SiOwAa_yAv8SJiu=s250" alt="" />
</div>
CSS
img {
width: auto;
height: 100%;
}
.horizontal {
width: 400px;
height: 120px;
background: red;
}
.vertical {
width: 120px;
height: 400px;
background: blue;
}
JavaScript
// Define plugin 'containImg'
$.fn.containImg = function(){
this.each(function(){
// Set variables
var $t = $(this),
$p = $t.parent('div'),
pw = $p.width(),
ph = $p.height(),
// Figure if width or height should be 100%
iw = ( pw / ph >= 1 ) ? 'auto' : '100%',
ih = ( iw == 'auto' ) ? '100%' : 'auto';
// Set dimensions
$t.css({
'width': iw,
'height': ih
});
});
}
// Call plugin
$('img').containImg();