How to set maximum height or width for:
$img_attributes= ' height=100 width=100 '. 'alt="'.$product['product_name'].'"';
How to set maximum height or width for:
$img_attributes= ' height=100 width=100 '. 'alt="'.$product['product_name'].'"';
Well, there are the max-height
and max-width
CSS properties, aren't they? THey work in all major browsers except IE 6 and in IE 7.
You should check this answer for general information : Proportional image resize.
If you want to have an image resized without using server side I suggest you to user Javascript. Here is a tutorial.
In short you have a JavaScript function that will return the new Width and Height:
function scaleSize(maxW, maxH, currW, currH){
var ratio = currH / currW;
if(currW >= maxW){
currW = maxW;
currH = currW * ratio;
} else >if(currH >= maxH){
currH = maxH;
currW = currH / ratio;
}
return [currW, currH];
}
With this function you can set the image width and height:
img.width = newW;
img.height = newH;
But, the best way would be to do it at server side. This will prevent to have a weird effect on client side.
The following style will cause all images using the "MaxSized" css class to have a max height of 100px and a max width of 100px. If an image is smaller, it will not be stretched.
<style>
IMG.MaxSized
{
max-width: 100px;
max-height: 100px;
}
</style>
As mentioned by Pekka, you'll have to have a XHTML 1.0 Strict DTD in order for this to work in modern versions of IE, but I personally believe this is the appropriate approach.
As the top answer says, you can use max-height
or max-width
CSS properties. But these properties don't behave in the same way. To keep the ratio of the image, you have to set height and width to 100%, and then set max-width
. If you set max-height
the ratio is not preserved.
So:
<img src="image.png" style="height: 100%; width: 100%; max-width: 400px" alt=" "/>
does preserve the ratio, but
<img src="image.png" style="height: 100%; width: 100%; max-height: 400px" alt=" "/>
does not. This is because (as far as I understood) HTML will first set the width and then the height. So in the second case the width is set at 100% but the height is limited, which might result in distorting the image. In the first case, the width is set with a maximum limit, and the height is adjusted accordingly, hence preserving the image dimensions.