Home / Language / English / Keep aspect ratio of img

Keep aspect ratio of img

I’d like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:
img src="whatever.jpeg" width="100%" height="100%" />
It just stretches the image and messes up the aspect ratio. How do I solve this so the image has the correct aspect ratio while scaling to the maximum size possible ?

function resizeToMax(id){
    myImage = new Image()
    var img = document.getElementById(id);
    myImage.src = img.src;
    if(myImage.width / document.body.clientWidth > myImage.height / document.body.clientHeight){
        img.style.width = "100%";
    } else {
        img.style.height = "100%";
<img id="image" src="test.gif" onload="resizeToMax(this.id)">

About Mohammad Khazab

Leave a Reply

%d bloggers like this: