How do I get an image to size with web page and keep proportions using CSS?

1 week ago 16
ARTICLE AD BOX

I would like to have an image show up on a page at 900x600 if the page is large enough, but resize down with the same aspect ratio if the screen gets smaller. I can get the image do that using object-fit: contain; but <img> HTML element still ends up filling the full width and/or height. On my production site, I have more divs with padding and fancy borders around the image so this will not work for me. Is there any way to get the <img> element to size down with the same aspect ratio as the original 900x600?

I need to specify the size of the image so that the image frame is correct whether the image has fully downloaded or not.

I've tried removing the height : 600px; from the CSS and it works perfectly if I make the screen narrow. However, when the display get short, then the image starts to distort.

I'm thinking that clamp in CSS might be the solution but I have not been able to figure that out.

As I will have multiple images, the 900x600 will not be the size for for each image that I have.

Test Image

img.fit { --border-width : 10px; max-width: 100%; max-height: 100%; position : absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: cyan; outline: var(--border-width) solid red; outline-offset: calc(-1 * var(--border-width)); /* aspect-ratio : 9 / 6; */ width : 900px; height : 600px; object-fit: contain; /* not what I want, but close */ } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <h1>Test</h1> <img class="fit" src="https://i.sstatic.net/6DPT74BM.jpg"> </body> </html>

Mike McCollister's user avatar

Read Entire Article