Loading and resizing images dynamically

HTML / Javascript - I want to load images dynamically, and the images I am about to load may have different aspect ratios.

I want the images to fit within a specific area of ​​the containing div - an area of ​​40% of the containing div's width and 80% of its height. Since they have different proportions, of course they won't always use this entire area, but I want to resize them so that they don't go over the border. But I don't know in advance if I should specify the width or height (and the partner attribute for auto), since I don't know what the aspect ratio of the image will be ahead of time.

Is there a CSS way to do this? Or do I need to calculate the required width using javascript?

PS I only need to do this in Firefox 3.5!

+2


source to share


2 answers


My solution was to provide a container div that anchored the object to the size I wanted:

#img_container {
  width: 48%;
  height: 80%;
}

      

Then, for the image itself, I assigned the max-width and max-height, which are recognized by firefox:



#img_container img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

      

This way the image automatically adjusts the maximum to the width of the container, but maintains the correct aspect ratio. Hooray!

+1


source


Your server can find out the dimensions of the images and send this information when the image is requested. Otherwise, you will need to wait for the image to load before its dimensions are available to javascript.

However, there is another way. Request an image by informing the server about the amount of space you have. It can then generate a suitable version of the image and cache it before sending an image that already matches the exact size up to the browser.

Update Another way that might be acceptable to you is to set the container div so that it ...



.mydiv { overflow: hidden; }

      

Then set the image to the height and auto

width. This will crop over wide images to the left and right of the image. If this is acceptable in your case, this is a very simple solution.

+1


source







All Articles