Scale Images UP to fit fixed container
by karim79
HTML
<div id="first">
<img src="http://i.ebayimg.com/00/$(KGrHqR,!mIE+ubCNtE8BQKNr8tfpg~~_02.JPG"/>
</div>
<br />
<div id="second">
<img src="http://i.ebayimg.com/00/$(KGrHqZ,!pwE-)NLVfSIBPsT0CHb3g~~_02.JPG"/>
</div>
CSS
#first, #second {
height: 300px;
width: 300px;
max-height: 300px;
max-width: 300px;
background-color: yellow;
}
img {
max-height: 300px;
max-width: 300px;
}
JavaScript
$.fn.upscaleToParent = function ($parentContainer) {
var width,
height,
containerHeight,
containerWidth,
ratio = 0,
$p = $parentContainer;
if (!$p || !$p.length) {
$p = $(this).parent();
}
return this.each(function() {
width = $(this).width();
height = $(this).height();
containerHeight = $p.height();
containerWidth = $p.width();
if (width > height && width != containerWidth) {
ratio = containerWidth / width;
$(this).css("width", containerWidth + "px");
$(this).css("height", height * ratio + "px");
}
if (height > width && height != containerHeight) {
ratio = containerHeight / height;
$(this).css("height", height * ratio + "px");
$(this).css("width", width * ratio + "px");
}
});
};
$("img").upscaleToParent();