Sainath Mallidi
Sainath Mallidi

Reputation: 515

Scaling images in HTML

I have to display a bunch of images in a page. Images are of different size, some very wide and some very thin. I want to put them all in a container of fixed width and fixed height.

Say if image is smaller, we retain the size and put it at the center of container. if image is bigger, we scale it down according to the prominent direction.

Our container is 500x500 and image is say 1000x400, then it will be scaled like 500x200. Similarly if image is 400x1000, then scaled image is 200x500. Is this doable with just html/css. Any help is appreciated. Thanks.

Upvotes: 3

Views: 923

Answers (5)

Prashant
Prashant

Reputation: 15

You can use width and height CSS properties to get the effect you want:

container img {

width:500px;
height:500px:

}

Be aware that this work in all browsers.

Thanks Ptiwari.

Upvotes: -1

Yan Ivanov
Yan Ivanov

Reputation: 196

The best way to do it on the server. Or manually before uploading them (if it's possible).

Upvotes: 0

Daniel
Daniel

Reputation: 31609

No. It's not fully doable with htm and css.

img{ width: 100% }

will make 1000x400 image to appear as 500x200 bu 400x1000 will appear as 500x1200.

You can use javascrpt like:

function scaleimage(id)
{
    var image = document.getElementById(id);
    if(image.offsetWidth > image.offsetHeight)
    {
         if(image.offsetWidth > 500)
         {
             image.offsetHeight = image.offsetHeight * 500 / image.offsetWidth;
             image.offsetWidth = 500;
         }
     }
     else
     {
         if(image.offsetHeight > 500)
         {
             image.offsetWidth = image.offsetWidth * 500 / image.offsetHeiht;
             image.offsetHeight = 500;
          }
    }
}  

Sorry for poor formating, seems like my iPhone doesn't support it.

Upvotes: 1

Yisroel
Yisroel

Reputation: 8174

You'll get much better results if you resize the images on the server. Resizing in the browser means the client is downloading much larger files than necessary, and the resizing quality is not great.

Upvotes: 3

Darko
Darko

Reputation: 38910

You can use max-width and max-height CSS properties to get the effect you want:

#container img {
    max-width:500px;
    max-height:500px:
}

Be aware that this does not work in IE6. To make it work there you may need to either scale the image serverside OR use expressions which are nasty. There are other workarounds which you can find on google :)

Upvotes: 4

Related Questions