使用CSS按比例调整img(警告:预设最大宽度/高度)

时间:2022-11-19 13:06:27

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.)

我有一个超大图像文件,所以我设置所需的最大宽度/高度(以像素为单位)。现在我希望该图像在页面调整大小的同时缩小,同时保持纵横比。 (具体来说,在Chrome浏览器中,如果相关的话。)

<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.

我不能为我的生活得到这个工作。我尝试设置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:

和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).

它可以工作,它可以两种方式扩展......当图像缩小时,它有时会在图像和侧边框之间留下巨大的空白区域。但是我认为当你设置img高度时,这比上面/下面的大空白间隙更好。至少现在它不会替换我的文本(在上方/下方,而不是在图像周围)。

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?

只有真正的解决方案似乎是没有国界。在美学上并不是很好,但我可能不得不认为它“足够好”,除非有人有更好的答案吗?

1 个解决方案

#1


1  

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.

我使用你的图像进行了一些更改,我认为这是像你描述的那样调整大小。

#1


1  

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.

我使用你的图像进行了一些更改,我认为这是像你描述的那样调整大小。