Autofit an image in a div using JQuery

I had a problem with one of my current projects where I was supposed to have an image enclosed in a div with fixed dimensions.

<div id="resize-div">
<img src="someimage.jpg", :id="resize-div">
</div>

For the dimensions of the div, you can set it inline or use css file:

#resize-div {
width:466px;
height:133px;
}

Now since not all images will fit this aspect ratio you’ll encounter problems easily enough. With images smaller than the div, I had little problem letting the css to handle it so it’s situated perfectly center in the div. I didn’t include it here to shorten the codes i need to display :).

Judging from the code shown above, you’ll not that if you have larger images that exceeded the div’s set height and width (especially those width different aspect ratios), a pure css solution simply won’t work (or at least I couldn’t make it work…. :/) so I thought of using JQuery to work it out for me.

Here’s my script to autofit images in a div using JQuery.

$(function(){
	var divElem = $("#resize-div");
	var maxht = divElem.height();
	var maxwdt = divElem.width();
	var imgElem = $("#resize-image");
	var ht = imgElem.height();
	var wdt = imgElem.width();
	if (ht < wdt){
		if (wdt > maxwdt)
			$("#resize-image").css({'height' : "auto", 'width' : maxwdt});
		else
			$("#resize-image").css({'height' : "auto", 'width' : wdt});
	}
	else if (ht > wdt){
		if (ht > maxht)
			$("#resize-image").css({'height' : maxht, 'width' : "auto"});
		else
			$("#resize-image").css({'height' : ht, 'width' : "auto"});
	}
});

3 Comments

  1. You must place that code in in an window.load ($. load() in jQuery) handler, so that you get reliable values for the image dimensions. They are not available until all referenced images are completely loaded.

  2. It will be nice to see how the code is integrated i a real live page. A demo will go a long way. Thanks

  3. Very useful, thx for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *