简体   繁体   English

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

[英]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.) (特别是在 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.我尝试设置最大高度。

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.但是我认为当您设置 img 高度时,这比上方/下方的大空白间隙要好。 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?在美学上不是很好,但除非有人有更好的答案,否则我可能不得不认为它“足够好”?

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.我使用您的图像进行了一些更改,我认为这是像您描述的那样调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM