Center image in fixed size div (Center Thumbnail Image)

This little script shrinks, and align image depending of their orientation. Image is rounded with div ho has fixed width and hight, and also a style set to overflow:hidden. The script actual recognize the image orientation and ad to image a margin-left or margin-top in minus atribute to style depending of a image vertical or horizontal orientation.


The math is simple

Say image is vertical; to get a normal aspect ratio of image first wee need to calculate the image width. If wee wont to shrink image to 160px height then y=160px and x=img.width/img.height*y

If image is horisontal then wee haw x=160px and nead to calcualate y. y=img.height/img.width*x

Now that wee haw x and y depending on image orientation wee calculate the margin-left or margin-top atribute

If image horisontal then margin-left=-(x-y)/2(px)

If image vertical then margin-top=- (y-x)/2(px)

And that’s it, the math is ower now the fun part;

Add jQuary call:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

Then some CSS:

<style type="text/css">
.thumb {
width:160px;
height:160px;
overflow:hidden;
}
</style>

Mix it with some javascript nad jQuary:

<script type="text/javascript">
window.onload = function() {
  var images = $(".image_center");
  for(i=0; i<images.length; i++)
     images[i].onload = centerImage(images[i]);

  function centerImage(img) {
   if (img.width > img.height ) {
   var y = 160;
   var x = img.width/img.height*y;
   var marx = (x-y)/2;
   img.style.height = y+"px";
   img.style.marginLeft = -(marx) + "px";
   }
   if (img.width < img.height ) {
   var x = 160;
   var y = img.height/img.width*x;
   var mary = (y-x)/2;
   img.style.width = x+"px";
   img.style.marginTop = -(mary) + "px";
   }
  }
}
</script>

Add serve it cold with the images in HTML:

<div class="thumb"><img class="image_center" src="sa.jpg" alt="#" /></div>
<div class="thumb"><img class="image_center" src="sb.jpg" alt="#" /></div>

See demo and download this script!

 

You may also like...

Leave a Reply

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

Captcha Captcha Reload

This site uses Akismet to reduce spam. Learn how your comment data is processed.