adit
adit

Reputation: 33674

resizing and centering an <img> inside a div and keeping aspect ratio

I have a div that has a fixed size of 500x500. Inside this div I have an image tag which can be dynamic. Meaning that it can have a size of a square, a rectangle (width > height), or a vertical rectangle (height > width). The issue is that I don't want this image to be squished, I wanted to keep the aspect ratio of the image. So say the image size is 1000x250, then I want it to be resized as 500x125 and then centered on this 500x500 box. If the size is 500x1000 then we wanted it to be resized as 250x500 and then centered with white spacing on the left and right.

Is there an easy way to do this using purely css or do I need javascript in order to do this? and how?

Here's the structure of what I 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>

Upvotes: 1

Views: 2441

Answers (3)

Francis Kim
Francis Kim

Reputation: 4285

Updated for 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 and width (unitless) and divide by 2
    var hWide = ($(this).width()) / 2; //half the image's width
    var hTall = ($(this).height()) / 2; //half the image's height, etc.

    // attach negative and pixel for 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/

Upvotes: 1

Qiqi Abaziz
Qiqi Abaziz

Reputation: 3353

If you're consider to use jQuery, then you can have a look at the ImgCenter jQuery plugin here.

Upvotes: 0

dave
dave

Reputation: 64707

I think you can do:

 #conatiner {
    line-height:500px;
    height:500px;
    width:500px;
}
#img {
  max-width: 100%;
  max-height:100%;
  display: block;
  margin: 0 auto;
  vertical-align: middle;
}

minimal partial example here: http://jsfiddle.net/cahs4/

I didn't do the vertical alignment but you can see what I mean

Upvotes: 0

Related Questions