Resizing image to fit its container

Posted by jack moore on Stack Overflow See other posts from Stack Overflow or by jack moore
Published on 2010-03-09T03:52:11Z Indexed on 2010/03/09 4:06 UTC
Read the original article Hit count: 301

Filed under:
|
#foo {width: 300px; height: 400px; overflow: hidden;}

<div id="foo"></div>

this.someimage = randomImageUrl;
$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";

Now, the picture could be 200x200 or 1100x400 ... it's totally random. I can just stretch it (or reduce its size) by using:

.fooimage {width: 300px; height: 400px;}

$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";

Or I could test its size:

imgHeight = newImg.height; 
imgWidth = newImg.width;

... and maybe something like this:

if(imgHeight >400){
   $("foo").innerHTML = "<img src='"+this.someimage+"' height='400' />";
}

and browsers will do the rest.

But there must be something better. Any ideas? Thanks! :)

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about prototype