javascript - resizing and centering an <img> inside a div and keeping aspect ratio -
i have div has fixed size of 500x500. inside div have image tag can dynamic. meaning can have size of square, rectangle (width > height), or vertical rectangle (height > width). issue don't want image squished, wanted keep aspect ratio of image. image size 1000x250, want resized 500x125 , centered on 500x500 box. if size 500x1000 wanted resized 250x500 , centered white spacing on left , right.
is there easy way using purely css or need javascript in order this? , how?
here's structure of have now:
<div class="product-large" style="position: relative; overflow: hidden;"><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" alt=""><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" class="zoomimg" style="position: absolute; top: -236.43249427917618px; left: -188.05491990846681px; opacity: 0; width: 1024px; height: 714px; border: none; max-width: none;"></div>
updated vertical centering - jquery required.
html
<div class="product-large"> <img src="image1.jpg"> </div> <div class="product-large"> <img src="image2.jpg"> </div>
css
.product-large { width:500px; height:500px; border:1px red solid; position:relative; } .product-large img { max-width:500px; max-height:500px; width:auto; height:auto; position:absolute; top:50%; left:50%; }
javascript (jquery)
$(".product-large img").each(function () { //get height , width (unitless) , divide 2 var hwide = ($(this).width()) / 2; //half image's width var htall = ($(this).height()) / 2; //half image's height, etc. // attach negative , pixel css rule hwide = '-' + hwide + 'px'; htall = '-' + htall + 'px'; $(this).addclass("js-fix").css({ "margin-left": hwide, "margin-top": htall }); });
new fiddle: http://jsfiddle.net/asvdk/2/
Comments
Post a Comment