Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set maximum height for $img but keep proportions

How to set maximum height or width for:

$img_attributes= ' height=100 width=100 '. 'alt="'.$product['product_name'].'"';

like image 282
Chris Avatar asked Dec 22 '09 18:12

Chris


2 Answers

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.

like image 121
Joris Meys Avatar answered Sep 28 '22 10:09

Joris Meys


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.

like image 24
Pekka Avatar answered Sep 28 '22 09:09

Pekka