在具有最大宽度的CSS中按比例缩放图像

问题描述:

现在,我使用最大宽度缩放图像以适应。然而,它们不按比例缩放。有没有办法导致这种情况发生?我对Javascript / jQuery开放。

Right now, I'm using max-width to scale images to fit. However, they don't scale proportionally. Is there a way to cause this to happen? I'm open to Javascript/jQuery.

如果可能,有没有办法做到这一点,而不知道图像的原始尺寸(也许使用Javascript / jQuery )

If possible, is there a way to do this without knowing the original dimensions of the image (maybe determine this using Javascript/jQuery)?

您需要指定原始宽度和高度:

You need to specify the original width and height:

<img src="/whatever" width="100" height="200" alt="Whatever" />

然后在CSS中使用这样的东西:

And then use something like this in the CSS:

#content img { max-width: 100%; height: auto }

如果没有宽度和高度,可以使用jQuery但您的里程可能会有所不同:

You could try this with jQuery if you don't have the width and height up front, but your mileage may vary:

$(function(){
    $('#content img').load(function(){
       var $img = $(this);
       $img.attr('width', $img.width()).attr('height', $img.height());
    });
});

显然,用任何选择器替换 #content 想将功能范围限定为

Obviously replace #content with whatever selector you want to scope the functionality to.