Question

I am adding images into a page that are all different aspect ratios (some wide, some tall etc).

what is the best way to get all the images to display the more or less the same size but not be squashed/stretched?

I have tried

<img src='admin/userpics/$prodID.jpg' height='50%'>

This doesn't seem to make images the same?

Was it helpful?

Solution

I'd use CSS.

img {
   max-height: 200px; 
   max-width: 200px; 
    }

OTHER TIPS

simply set the width or height to a fixed value, and the other value to auto

<img src='admin/userpics/$prodID.jpg' style='width:100px;height:auto;'>

or

<img src='admin/userpics/$prodID.jpg' style='height:100px;width:auto;'>

what ever you prefer, the aspect ratio with be always correct

If you don't like img tags (as me), you could use this (if you won't target <= IE8 as Brad pointed out):

div.image {
    background-size:cover;
    background-position:center;
    display:block;
    width:30%;
    height:30%;
}


<div class="image" style="background-image:url(admin/userpics/$prodID.jpg)"></div>

Proof: http://jsbin.com/ekogaz/1/edit See how the image always stays in center, but still is cropped. You can add as many of these as possible. Also, you can use % (or like 100px). Try to resize the window and you'll see that it works then too.

enter image description here

<img src='admin/userpics/$prodID.jpg' style='height: 200px; width: auto;'>

Use values in pixels, instead of a percentage. Like this:

<img src="smiley.gif" alt="Smiley face" height="42" width="42"> 

You already got many useful answers for displaying resized images with html/css, but i would recommend you create thumbnails and use them instead. That way you will avoid loading the full resolution images even if you just need small resolution thumbs, which is important especially if the images are in high resolution or you are building some kind of gallery. Also you will have control over the quality of downsampling done on your image, which is much better then some browsers do. Since you use PHP check out this library for example: phpThumb

You can define the maximum width and height you want to use, and resize image keeping the aspect ratio.

http://jsfiddle.net/7TDCA/

HTML:

<div class="img-wrapper">
    <img src="http://i.imgur.com/Himba.png" alt="" title="" />
</div>

<div class="img-wrapper">
    <img src="http://cdn.fotocommunity.com/Natur/Tiere/Pfau-Hochformat-a18613762.jpg" alt=""     title="" />
</div>

CSS:

.img-wrapper {
    margin: 50px auto;
    width: 50%;
    height: 250px;
    overflow: hidden;
}

.img-wrapper img {
    width: 100%;
    height: auto;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top