Posts Photos Archives About

HTML/Javascript - I want to load images dynamically, and the images I'm going to load can be of varying aspect ratios.

I want the images to fit into a specific area of the containing div - an area 40% of the containing div's width and 80% of its height. Since they have varying aspect ratios, of course they will not always use up this entire area, but I want to resize them such that they don't exceed the bounds. But I don't know ahead of time whether I should specify the width or the height (and the partner attribute to auto) since I don't know what the aspect ratio of the images will be ahead of time.

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

PS I only need to do this in Firefox 3.5!


Rik Heywood said...

Your server can find out the dimensions of the images and send this information along when you request an image. Failing that, you will need to wait for the image to load before its dimensions will be available to javascript.

However, there is another way. Request the image, telling the server the dimensions of the space you have. It can then generate a suitable version of the image and cache this, before sending the image that is already exactly the right size down to the browser.

Update One other way, that may be acceptable to you is to set the container div like so...

.mydiv { overflow: hidden; }

Then set the image to be fixed in height and auto for width. This will cause over-wide images to be clipped on the left and right of the image. If this is acceptable in your case, then this is a very simple solution.

rahul said...

Do you need to keep the aspect ratio to the same as of the original image?

Roy Tang said...

My solution was to provide a container div that would bound the object to the needed size:

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

Then for the image, itself I assigned 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 auto-adjusts itself at most to the width of the container, but keeps the correct aspect ratio. Hooray!