Is there anyway to maintain following aspect ratio with either maximum width or maximum height, below are the situations I'm facing. maximum width or height should be 500px
400x300 image - no resizing (both sides below 500 maximum size)
500x500 image - no resizing (both sides at exactly 500 maximum size).
600x400 image - resize to 500x333 (preserves same ratio) as one side is over 500 pixels.
1000x1200 image -resize to 417x500 (preserves same ratio), as both sides are over 500 pixels
Setting the CSS properties max-width
and max-height
to limiting values, while leaving the image with auto
for it's width
and height
can be used to maintain aspect ratio while restricting the max size like this:
img {
display: block;
width: auto;
height: auto;
max-width: 500px;
max-height: 500px;
}
<img src="https://via.placeholder.com/50x50" />
<img src="https://via.placeholder.com/500x100" />
<img src="https://via.placeholder.com/100x500" />
<img src="https://via.placeholder.com/1000x200" />
<img src="https://via.placeholder.com/200x1000" />
The images larger than 500px will be resized to fit the limit, while smaller images will retain their original size.