开发者

Scaling images in HTML

开发者 https://www.devze.com 2023-01-07 01:00 出处:网络
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.

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 smal开发者_C百科ler, 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.


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 :)


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号