Auto Fit Images to DIV with PHP – Scale and Centre

Writing simple PHP functions can sometimes take up a lot of your time, so when you find one that suits your needs it can save a lot of time, sometimes there is no other option but to write your own.  Here’s a simple, but useful function I wrote to auto fit images to a set size DIV.

If you have ever had clients try to upload their own images to a website, you’ll know that the quality an uniformity can be erratic at best.

So when I created a CMS for one particular client I decided to create a simple function that would allow the website to keep it’s uniform look even though the client would not bother with correctly sizing the images before uploading.

The function looks like this:-

function scaleAndCenter($divWidth, $divHeight, $image){

 list($width, $height) = getimagesize($image);

 $scale['newHeight']=$height * $scale['widthRatio'];
 $scale['newWidth']=$width * $scale['heightRatio'];


 return $scale;



echo'<p>The image scaled and centered to fit a 320 x 225 px DIV</p>
 <div style="width:320px; height:225px; overflow:hidden;">
 <img src="'.$image.'" width="'.$productThumb['newWidth'].'" height="'.$productThumb['newHeight'].'" 
style="margin-top:-'.$productThumb['marginTop'].'px; margin-left:-'.$productThumb['marginLeft'].'px"/>

auto fit images

To explain a little further you can see that the height and width of the <div> we are attempting to place the image inside is 320×225, with any overflow hidden.  So we call the function, sending these dimensions, plus the location of our image to the function.

The function works out which orientation the image is and calculates the necessary proportions for the image to best fit into the DIV.  This particular example is more sympathetic to square or landscape images.  Portrait images will still be scaled and centred, but the image will probably not look the best.

If you have lots of different sized images, or mixed portrait and landscaped images you may have to consider editing the images before the upload or using one of the many jQuery libraries to give the user the ability to crop the image after upload.

If you want to see this code in action, visit the demo page –


This entry was posted in PHP, Website Development and tagged , , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post. Both comments and trackbacks are currently closed.