我如何为IMG设置最小和最大尺寸并保持长宽比

  • 本文关键字:IMG 设置 html css
  • 更新时间 :
  • 英文 :


所以我有一个img框,用户可以在其上丢弃图像。CSS当前确保使用此CSS

将其作为300x300图像显示为300x300的图像

因此,将增加200x200的图像以准确地拟合,并将图像400x400降低以完全适合300x300 IMG元素。

.largeartwork img {
    max-width:300px;
    max-height:300px;
    min-width:300px;
    min-height:300px;
    border: 3px solid black;
}

这可以正常工作,但是我想为非正方形图像做的事情尽可能地填充空间,但保留纵横比

例如,300x200的图像(300像素宽,200像素高(应仅填充宽度,但不能填充高度,而与600x400 etcetera的图像相同。

请注意可能的重复链接帖子上的答案已过时,不那么好

根据我的评论,使用最小/最大宽度和高度不能保证保留图像纵横比,因为在调整图像大小时,浏览器需要确定哪个维度(水平或垂直(优先考虑。由于在这种情况下无法决定,因此任何非方面的图像都会被压制或拉伸,因为它们的纵横比与您指定的图像不匹配。

您的难题有两种解决方案:一种是使用object-fit,它得到了广泛支持,但不幸的是,在Internet Explorer中没有。样本标记看起来像这样:

<div class="largeartwork">
  <img src="/path/to/image" />
</div>

您的CSS将是:

.largeartwork img {
    width: 300px;
    height: 300px;
    border: 3px solid black;
    object-fit: contain;
}

请参阅下面的概念证明代码段:

.largeartwork img {
    width: 300px;
    height: 300px;
    border: 3px solid black;
    object-fit: contain;
}
<!-- Landscape -->
<div class="largeartwork">
  <img src="https://via.placeholder.com/350x150" />
</div>
<!-- Portrait -->
<div class="largeartwork">
  <img src="https://via.placeholder.com/150x350" />
</div>
<!-- Small square image -->
<div class="largeartwork">
  <img src="https://via.placeholder.com/100x100" />
</div>
<!-- Large square image -->
<div class="largeartwork">
  <img src="https://via.placeholder.com/400x400" />
</div>


另一种解决方案将是使用background-image。您将必须依靠JS将图像源注入元素的背景。优势是background-size: contain也得到了非常广泛的支持,即使在Internet Explorer 9中。示例代码:

<div class="largeartwork" style="background-image: url(/path/to/image);"></div>

和您的CSS:

.largeartwork {
    width: 300px;
    height: 300px;
    border: 3px solid black;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center center;
}

请参阅下面的概念验证代码:

.largeartwork {
  width: 300px;
  height: 300px;
  border: 3px solid black;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
<div class="largeartwork" style="background-image: url('https://via.placeholder.com/350x150')"></div>
<div class="largeartwork" style="background-image: url('https://via.placeholder.com/150x350')"></div>
<div class="largeartwork" style="background-image: url('https://via.placeholder.com/100x100')"></div>
<div class="largeartwork" style="background-image: url('https://via.placeholder.com/400x400')"></div>

当宽度或高度的最大值和最小值与此相同时,则表示固定值如下:

.largeartwork img {
    width:300px;
    height:300px;
}

在您的情况下,您可以通过此方法解决问题:

当用户丢弃图像文件时,您可以检查图像的哪一侧更大,您可以将正确的类添加到图像标签中。例如:

创建这样的CSS类:

.largeartwork img.biggerwidth {
    width: 300px;
    height: auto;
}
.largeartwork img.biggerheight {
    width: auto;
    height:300px;
}

,当用户像200x500像素一样删除图像时,您可以像这样创建图像:

<img src="..." class="biggerheight">

为什么这比背景图像和对象拟合更好?

在这些方法上,如果图像大小不涵盖所有元素区域,则您将在元素上获得空白。由于您在元素上使用边框,因此这些方法始终在指定的最大大小周围创建边框。

最新更新