如何自动调整大图像的大小,使其适合较小宽度的div容器,同时保持其宽高比?


示例:stackoverflow.com-当图像插入到编辑器面板上,并且图像太大而无法放到页面上时,图像将自动调整大小。


当前回答

此解决方案不会拉伸图像并填充整个容器,但会剪切部分图像。

HTML格式:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

其他回答

所有提供的答案,包括已接受的答案,都只能在假设div包装器大小固定的情况下工作。因此,无论div包装器的大小如何,这都是如何实现的,如果您开发响应页面,这非常有用:

在DIV选择器中编写以下声明:

width: 8.33% /* Or whatever percentage you want your div to take */
max-height: anyValueYouWant /* (In px or %) */

然后将这些声明放入IMG选择器中:

width: "100%" /* Obligatory */
max-height: anyValueYouWant /* (In px or %) */

非常重要:

对于DIV和IMG选择器,maxHeight的值必须相同。

我看到很多人都建议对象匹配,这是一个不错的选择。但是,如果您希望它也能在较旧的浏览器中工作,还有另一种方法可以轻松实现。

这很简单。我采用的方法是将图像放置在容器内,然后使用组合将其放置在中心:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

一旦它在中心,我给图像,

// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;

// For horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;

这使图像获得对象拟合的效果:覆盖。


以下是上述逻辑的演示。

https://jsfiddle.net/furqan_694/s3xLe1gp/

此逻辑适用于所有浏览器。

此解决方案不会拉伸图像并填充整个容器,但会剪切部分图像。

HTML格式:

 <div><img src="/images/image.png"></div>

CSS:

div {
    width: 100%;
    height: 10em;
    overflow: hidden;

img {
    min-width: 100%;
    min-height: 100%;
}

我有更好的解决方案,不需要任何JavaScript。它反应灵敏,我经常使用它。通常需要将任何纵横比的图像与具有指定纵横比的容器元素相匹配。必须让这一切都能完全响应。

/*仅用于此演示*/.容器{最大宽度:300px;边距:0自动;}.img框架{方框阴影:3px 3px 6px rgba(0,0,0、.15);背景:#ee0;边距:20px自动;}/*这适用于具有指定纵横比的响应容器*/.纵横比{位置:相对;}.方面-1-1{填充底部:100%;}.方面-4-3{填料底部:75%;}方面-16-9{垫底:56.25%;}/*这是关键部分-定位并将图像适配到容器*/.fit img{位置:绝对;顶部:0;右:0;底部:0;左:0;边距:自动;最大宽度:80%;最大高度:90%}.fit img底部{顶部:自动;}.紧密贴合{最大宽度:100%;最大高度:100%}<div class=“container”><div class=“纵横比aspect-ratio-1-1 img帧”><img src=“https://via.placeholder.com/400x300“class=”fit img“alt=”sample“></div><div class=“纵横比aspect-ratio-4-3 img帧”><img src=“https://via.placeholder.com/400x300“class=”fit img fit img tight“alt=”sample“></div><div class=“纵横比aspect-ratio-16-9 img帧”><img src=“https://via.placeholder.com/400x400“class=”fit img“alt=”sample“></div><div class=“纵横比aspect-ratio-16-9 img帧”><img src=“https://via.placeholder.com/300x400“class=”fit img fit img bottom“alt=”sample“></div></div>

您可以独立设置最大宽度和最大高度;图像将遵循最小的图像(取决于图像的值和纵横比)。您还可以将图像设置为按需对齐(例如,对于无限白色背景上的产品图片,您可以轻松地将其定位到中心底部)。

我使用以下代码修复了此问题:

<div class="container"><img src="image_url" /></div>
.container {
    height: 75px;
    width: 75px;
}

.container img {
    object-fit: cover;
    object-position: top;
    display: block;
    height: 100%;
    width: 100%;
}