使图像适合容器,无需对象适合:contain
下面的代码是制作图像的完美解决方案:
- 适合给定的容器
- 在容器中水平和垂直居中
- 使用最大可能的尺寸
- 而不改变宽高比
完美,除了库 html2canvas
不适用于 object-fit: contains;
(另请参阅 Html2canvas 忽略适合图像的对象)。
问题:如何在没有相对较新的 object-fit
的情况下获得与标准 CSS 规则相同的行为?
.container { width: 200px; height: 200px; background: blue; }
img { height: 100%; width: 100%; object-fit: contain; }
1:
<div class="container"><img src="https://via.placeholder.com/100x50"></div>
2:
<div class="container"><img src="https://via.placeholder.com/50x100"></div>
3:
<div class="container"><img src="https://via.placeholder.com/500x300"></div>
4:
<div class="container"><img src="https://via.placeholder.com/300x500"></div>
我尝试了 如何我是否可以自动调整图像大小以适应“div”容器?但它们不适用于前面显示的所有 4 种情况。
The following code is a perfect solution to make an image:
- fit in a given container
- be centered horizontally and vertically in the container
- use the maximum possible size
- without changing the aspect ratio
Perfect, except that the library html2canvas
doesn't work with object-fit: contain;
(see also Html2canvas Ignores Object fit for image).
Question: how to obtain the same behaviour with standard CSS rules, without the relatively-new object-fit
?
.container { width: 200px; height: 200px; background: blue; }
img { height: 100%; width: 100%; object-fit: contain; }
1:
<div class="container"><img src="https://via.placeholder.com/100x50"></div>
2:
<div class="container"><img src="https://via.placeholder.com/50x100"></div>
3:
<div class="container"><img src="https://via.placeholder.com/500x300"></div>
4:
<div class="container"><img src="https://via.placeholder.com/300x500"></div>
I've tried various answers from How do I auto-resize an image to fit a 'div' container? but they don't work in all the 4 cases shown before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
background-image
代替Use
background-image
instead正如我之前在评论中所说,如果没有
javascript
,对于小于容器的图像可能是不可能的,但如果你找不到CSS解决方案,我做了这个简单的例子:https://jsfiddle.net/zq7vw2y8/1/
编辑。我已经制作了另一个JSFIDDLE 具有非常紧凑的
script
并且没有jquery
As I said before in the comments maybe not possible without
javascript
for images smaller than containers but in case you won't find a css solution I have made this easy example:https://jsfiddle.net/zq7vw2y8/1/
Edit. I have made this other JSFIDDLE with much compact
script
and nojquery