N. River
N. River

Reputation: 21

Resize img proportionally with CSS (caveat: preset max-width/height)

I have an overlarge image file, so I set desired max-width/height in pixels. Now I want that image to shrink with page resize, while maintaining aspect ratio. (In Chrome browser specifically, if that's relevant.)

<img style="max-width: 700px" src="http://static.photocdn.pt/images/articles/2017/04/28/iStock-516651882.jpg">

I cannot for the life of me get this to work. I tried setting max-height.

img {
max-height: 100vh;
}

But while it resizes vertically very nicely, it doesn't resize horizontally. As in if the screen is too narrow, it overflows to the right.


UPDATE:

Okay, so best I've come up with is:

<img style="width: 700px" src="http://static.photocdn.pt/images/articles/2017/04/28/iStock-516651882.jpg">

and CSS:

img {
max-height: 100vh;
max-width 100%;
object-fit:scale-down;
}

It works, it scales both ways ... it sometimes leaves a huge white-space between the image and the side borders when the image is scaled down. But I suppose that's better than a big whitespace gap above/below when you set img height instead. At least now it's not displacing my text (which is above/below, not around the image).

Only real solution seems to be to go without borders. Not great aesthetically, but I may have to consider it 'good enough' unless someone has a better answer?

Upvotes: 2

Views: 2770

Answers (1)

Jay Hamilton
Jay Hamilton

Reputation: 114

This will work for a generic case. It will not go over the max, but will resize smaller appropriately.

<div style="max-width: 700px">
 <img style="height: auto; width: 100%"  
  src="http://static.photocdn.pt/images/articles/2017/04/28/iStock-516651882.jpg">
</div>

I made some changes using your image, I think this is resizing like you described.

Upvotes: 1

Related Questions