Set image max size

Viewed 15276

I need to set maximum height and width of a image in <img> tag. For example say max size is 400x400 px so if the image size is smaller than this then it will show the image as it is and if size is bigger then this then it should be compressed to this size. How can I do this in html or javascript?

6 Answers

You can also use object-fit: scale-down to make image fit a container size if it's too big and leave image size as is if it's smaller than the container.

CSS:

.img-scale-down {
    width: 100%;
    height: 100%;
    object-fit: scale-down;
    overflow: hidden;
}

HTML:

<div style="width: 400px;">
   <img src="myimage.jpg" class="img-scale-down"/>
</div>

In JavaScript you can use:

/* getting the image */
var img = document.createElement('img');
img.src = "img.png";

/* setting max width and height */
document.getElementById("id").appendChild(img).style.maxWidth = "400px";
document.getElementById("id").appendChild(img).style.maxHeight = "400px";

/* inserting image */
document.getElementById("id").appendChild(img);
Related