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?
Set image max size
Asked Answered
Set the max-width
and max-height
in CSS
max-width: 400px;
max-height: 400px;
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>
try using a div tag of that size and putting image inside:
<div style="width:400px; height400px;>
<img style="text-align:center; vertical-align:middle; max-width:400px; max-height:400px;" />
</div>
or something like that. The div is the full size and the image can only expand to its borders.
The way I did it:
- When the image is being uploaded I use a server side library to resize if the image is bigger (only). You always resize down, never up.
- Then on the client side I do not set the image size.
The image will be 400x400 only for those images that were exactly that size or bigger.
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);
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂 –
Goldofpleasure
img
{
max-width: 400px;
max-height: 400px;
}
Like so: http://jsfiddle.net/fMuVw/
© 2022 - 2024 — McMap. All rights reserved.