How can I proportionally scale down an <img> element with the shorter of its WxH set to a fixed number?


<div id="thumbnail">
  <img src="xxx">


border: 2px solid #ccc;
width: 50px;
height: 50px;
overflow: hidden;

Say the image size is greater than 50x50, is there any way that I can proportionally scale down the image so that the shorter of its width and height would become 50px? Note that the image can be in either portrait or landscape.


First load up the image in javascript to get its real dimensions.

var img = new Image('image.jpg');
var width = img.width;
var height = img.height;

Then determine which one has the larger height, and adjust them accordingly using the ratios.

if (width <= height) {
    var ratio = width/height;
    var newWidth = 50;
    var newHeight = 50 * ratio;
} else {
    var ratio = height/width;
    var newWidth = 50 * ratio;
    var newHeight = 50;

Then insert the image into the DOM using jQuery.

$('#imageContainer').append('<img src="' + img.src + '" style="width:' + newWidth + 'px; height:' + newHeight + 'px;" />');

Divide the width of the image by the height, that's your ratio. Then find what's the largest dimension, if it's the width, set the width = 50 * ratio, and height = 50; if it's the height set it height = 50 / ratio and the width = 50. Do you need Javascript code?

Need Your Help

Hibernate 2.1.6 or 3.x?

java hibernate java-ee architecture

We are in the process of revamping our persistence layer from some proprietary orm. Most of our developers are already familiar with hibernate 2 and also its gotchas. So we decided to stay with Hib...

What is a good design for an interface with optional components?

java oop design-patterns

Suppose I have an interface that supports a few potential operations:

Online exam web application

java javascript jsp servlets

I am developing an online exam using JSP/Servlets which is nearing completion. I'm planning to add timer function for the entire exam that shows elapsed time in minutes. How do I implement this wit...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.