views:

42

answers:

2

I've a 100*100 <div> in which I would like to display images of different sizes randomly without stretching them.

Note:The image should appear as origional, just resizing should be done inorder to place it in box

+1  A: 

Maybe this style will help you:

div {
   position:relative;
}

div img {
   max-width:100%;max-height:100%;
}
Miro
+1 but why the `position: relative`?
Pekka
beacuse i've set max-width,max-height to percentage, more you can read there: http://www.w3schools.com/css/pr_class_position.asp
Miro
A: 

here's a simple function to calculate your aspect ratio and size the image down. it takes the path to the file and the original width and height of the image. you can provide all that however you see fit. 'myElement' would be the id of your image element.

function loadImage(filename, width, height) {

    var aspect = width / height;
    var w, h;

    if (width > height) {
        w = 100;
        h = Math.round(100 / aspect);
    }
    else {
        h = 100;
        w = Math.round(100 * aspect);
    }

    var element = document.getElementById('myElement');
    element.src = filename;
    element.style.width = w + 'px';
    element.style.height = h + 'px';
}
lincolnk