views:

400

answers:

1

I've got a web page that displays a bunch of images. I want to make sure none of the images are greater than 200 pixels wide and 200 pixels in height. If one is, I'd like it scaled down so that the longest dimension is 200 pixels.

What's the best way to do this? CSS? JavaScript (jQuery okay)?

+2  A: 

Assuming jQuery:

var img = $(img), width = img.width(), height = img.height();
if(width == height) {
    img.width(200).height(200);
} else if(width > height) {
    img.height(Math.round(height / width * 200)).width(200);
} else {
    img.width(Math.round(width / height * 200)).height(200);
}

You may be able to just set the longest dimension and skip the ratio (if the width and height are not otherwise set in attributes, properties or CSS), but I haven't done browser testing to be sure if it works across the board.

eyelidlessness