在div内向上缩放图像和/或向下以使用CSS适合图像的最大边 [英] Scale image inside div up AND/OR down to fit largest side of image with CSS
问题描述
我在这里看了很多关于这个主题的Q& A但是如果存在的话就找不到确定的答案。
I've looked through A LOT of Q&A here on the topic but can't find a definitive answer if one exists.
我有一个动态宽度和高度的div,想要在其中放入任何大小的图像并保持纵横比。这可能是向上或向下缩放图像:
I have a div of dynamic width and height and want to fit any sized image inside of it and keep the aspect ratio. This could be scaling the image up or down:
我已经尝试了宽度,高度,最大宽度,最大高度,物体贴合等的每个组合我可以想到没有运气,总有至少一个失败的情况。我见过的大多数解决方案都涉及一些硬编码的最大宽度或高度值。是否有可能让所有上述情况仅使用CSS和动态大小的div容器?
I've tried every combo of width, height, max-width, max-height, Object-fit etc I can think of with no luck, there's always at least one case that fails. Most solutions I've seen involve some hard coded max-width or height values. Is it possible to get ALL above cases working only with CSS and a dynamically sized div container?
PS我的目标浏览器是Edge,如果这会产生影响。
PS my target browser is Edge if that makes a difference.
谢谢!!
推荐答案
这是一种方法。
使用 background:url(path / to / image)
将图像应用为css背景,然后使用 background-size
属性设置缩放以包含, background-size:contains
(参见小提琴, https://jsfiddle.net/mghgsk5e/ )。
Apply the image as an css background using background: url(path/to/image)
and then using the background-size
attribute to set the scaling to contain, background-size: contain
(see fiddle, https://jsfiddle.net/mghgsk5e/).
这篇关于在div内向上缩放图像和/或向下以使用CSS适合图像的最大边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!