Advertisement
Guest User

Center image in parent div

a guest
Sep 16th, 2014
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. params:
  3.     image - DOM element
  4.     div - parent div of image
  5.     scaleMode - 'scale' or 'scaleCrop'
  6. */
  7. function centerImageInDiv(image, div, scaleMode){
  8.     $(image).css({
  9.         width : "auto",
  10.         height : "auto"
  11.     });
  12.     if (!scaleMode) scaleMode = "scaleCrop";
  13.     var containerWidth = $(div).width();
  14.     var containerHeight = $(div).height();
  15.  
  16.     var imgWidth = image.width;
  17.     var imgHeight = image.height;
  18.  
  19.     var newWidth, newHeight;
  20.     if ((containerWidth / containerHeight < imgWidth / imgHeight) ^ (scaleMode != "scale")) {
  21.         newWidth = Math.min(containerWidth, imgWidth);
  22.         newHeight = ((imgHeight * Math.min(containerWidth, imgWidth)) / imgWidth) >> 0;
  23.     }
  24.     else {
  25.         newHeight = Math.min(containerHeight, imgHeight);
  26.         newWidth = ((imgWidth * Math.min(containerHeight, imgHeight)) / imgHeight) >> 0;
  27.     }
  28.  
  29.     $(image).css({
  30.         width : newWidth + "px",
  31.         height : newHeight + "px",
  32.         "margin-left" : ((containerWidth - newWidth) >> 1) + "px",
  33.         "margin-top" : ((containerHeight - newHeight) >> 1) + "px"
  34.     });
  35. }
  36.  
  37. // usage:
  38. image.on('load', function(){
  39.     centerImageInDiv(this, $(this).parent()[0], "scale");
  40. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement