'Make image fully responsive but maintain aspect ratio
I have problem where I have fully responsive webshop which works on resize, I need to make product box image to be in square box. So for example image 150x150, 150x100 and 100x150 needs to be centered by X/Y axis, without rasterizing and similar issues. I don't have option to hardcode sizes of product boxes so it must be responsive on changing width of browser.
So far I tried:
- Use 150x150 hidden placeholder in behind to maintain aspect ratio and over that add element which will contain image tag (tried width/height auto and 100%)
- Use 150x150 hidden placeholder in behind to maintain aspect ratio and over that add element which will contain element which has background image with contain/cover property, didn't work for me
- Writing script which will work on img load and create canvas to replace old image - does not work because of lazy load
so my limitations are:
- Can not use scripts because of lazy load images
- Can not hardcode sizes of image box in product box
- Can not use anything which is not supported by all browsers (for example
max-width: max-contentis not supported by IE11 and below) - I need to use img tag which provides sizes property to have all sizes needed on different dimensions
Thank you all in advance
Solution 1:[1]
Here's a simple snippet where the image is given max width and height. It will not go above its natural width and height but if it is too big for the area allowed it will shrink to fit without losing its aspect ratio.
The image is centered in its parent using flex.
div {
width: 20vw;
height: 20vw;
border: solid 1px black;
display: flex;
align-items: center;
justify-content: center;
}
img {
max-width: 100%;
max-height: 100%;
}
<div><img src="https://picsum.photos/id/1015/150/200"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | A Haworth |
