Mayur
Mayur

Reputation: 3097

Display Image in fixed size div

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

Upvotes: 0

Views: 4512

Answers (2)

lincolnk
lincolnk

Reputation: 11238

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';
}

Upvotes: 0

kravemir
kravemir

Reputation: 10986

Maybe this style will help you:

div {
   position:relative;
}

div img {
   max-width:100%;max-height:100%;
}

Upvotes: 2

Related Questions