我有一个固定尺寸为500x500的div。在这个div中,我有一个可以动态的图像标签。这意味着它可以具有正方形,矩形(宽度>高度)或垂直矩形(高度>宽度)的大小。问题是我不希望压缩该图像,我想保持图像的长宽比。假设图片尺寸为1000x250,那么我希望将其尺寸调整为500x125,然后将其放在此500x500框的中央。如果尺寸为500x1000,则我们希望将其调整为250x500,然后在左右两侧以白色间距居中。

有没有一种简单的方法可以使用纯CSS做到这一点,或者我需要JavaScript才能做到这一点?如何?

这是我现在所拥有的结构:

<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>

最佳答案

已更新为垂直居中-需要jQuery。

的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
    });
});


新提琴:http://jsfiddle.net/Asvdk/2/

关于javascript - 在div中调整<img>的大小并将其居中,并保持宽高比,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16352161/

10-12 22:19