• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2535
  • Last Modified:

How to scale images proportionally

I have a div which is 424px wide and 329px tall and must remain this size. This has an img control in it that I populate with an image. Sometimes this image might be landscape, sometimes portrait and the actual dimensions of each image might vary; most of the time, they are quite a bit larger than the dimensions of the aforementioned div.

The problem is that, if I want to load a landscape image into the img control inside that div, I don't want it to exceed the width of the div (424px), and therefore would like to scale it down to 424px, and have the height adjust accordingly/proportionally (Im aware that by keeping it proportional, it will obviously mean the height of this image wont always be the same height as the div, but shorter).

Likewise, if the image is portrait, I need to scale the image down so its no taller than the 329px tall div, and to scale the width proportionally (again, this will obviously mean the full width of the div will not be occupied but this is ok).

My CSS isn't great so any help with this would be much appreciated.

Thanks in advance.
1 Solution
Michel PlungjanIT ExpertCommented:
Try this:
aspect_ratio =1;
function initPage() {
  img = document.getElementById('img1');
  w = img.width
  h = img.height
  /* calculates aspect ratio */
  aspect_ratio = h/w;
  document.title="Aspect ratio:" +aspect_ratio + " wxh:"+w+"x"+h
function reloadImage(){
  if(!document.all) {
  } else {
  new_w = available_width-20;
  new_h = parseInt(new_w * aspect_ratio);
<body onLoad="initPage()" onResize="reloadImage()">
<div id="displayDiv" style="visibility:hidden"><img id="img2" src="http://www.rnrh.net/images/blog/hdr-sunset_soon_forgotten.jpg"></div>
<div style="visibility:hidden" width="1" height="1"><img id="img1" src="http://www.rnrh.net/images/blog/hdr-sunset_soon_forgotten.jpg"></div>

Open in new window


Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now