首页 > 解决方案 > CSS:在最大宽度和最大高度的响应式图像中保持纵横比

问题描述

(stackoverflow 上已经提出了类似的问题,但是这个问题有更多的限制,例如特定的最大宽度、最大高度、所需的特定高度和宽度,以及没有布局移位。)

问题:

我想要一个具有以下约束的响应式图像:

如何使用 CSS 实现这一点?

(如果 CSS 不能做到这一点,那么也许在 JavaScript 中?)

我试过的

我尝试了几个 CSS 功能,例如object-fit和 max-width: 100% 等,但在尝试修复另一个约束时,我总是遇到至少一个约束失败。例如,当屏幕尺寸减小时,object-fit 会在图像尺寸减小时为图像创建边距/填充,就好像图像边框没有减小一样。这在以下代码中进行了演示:

https://codepen.io/Devabc/pen/mdVvyKq

/* Should appear to the right of the Wombat */

.beside {
  float: left;
  background-color: lightgreen;
  border: 1px solid;
  height: 200px;
  width: 100px;
}


/* Should appear below the Wombat */

.below {
  background-color: red;
  border: 1px solid;
  width: 100px;
  height: 300px;
  clear: both;
}

img {
  display: block;
  float: left;
  max-width: 100%;
  max-height: 200px;
  border: 1px solid;
  
  /* Without this, aspect ratio is not normal. 
But with this, it creates an unwanted margin. */
  object-fit: scale-down;
  object-position: left;
}
<img 
height="533" 
width="799" 
src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/Vombatus_ursinus_-Maria_Island_National_Park.jpg/800px-Vombatus_ursinus_-Maria_Island_National_Park.jpg" 
/>

<div class="beside">This text should be directly to the right of the Wombat, without any margin between the Wombat and this text.</div>

<div class="below">This text should be directly below the Wombat, without any margin between this and the Wombat. 
The dimensions of the original Wombat img are:
width: 799px, height: 533px</div>

(绿色文本应该在 Wombat 的右侧,没有边距。但是 object-fit 会导致填充/边距与原始图像的长度一起出现。)

感觉好像这对 CSS 来说是不可能的,尽管现在这些要求不应该太多,响应式设计很重要。

如何使用 HTML/CSS 解决此问题?

标签: htmlcsslayoutresponsive-design

解决方案


多年来我一直在为此苦苦挣扎,但是就在今天,当您知道图像的纵横比时,我想出了一种方法,希望对您有所帮助:

首先在与图像比例对应的元素中定义一个--img-ratio CSS 自定义属性。imgheight / width

<!-- example of a square image (height / width = 1) -->
<img src="..." style="--img-ratio: 1" />

知道我们想要的最大高度是 200px(或者你可以使用泛型--max-height),我们知道等式的 2 个变量:

ratio = height / width
width = height * ratio

应用这个:

img {
  --max-height: 200px;
  /* Set a baseline width for your element */
  width: 100%;
  /* And limit it with our function above */
  max-width: calc(var(--max-height, 200px) * var(--img-ratio, 1));
}

我们去吧!即使在复杂的 flex 布局中,这也应该可以在没有额外边距的情况下限制高度。

如果这个答案不清楚,请告诉我,希望对您有所帮助

PS:如果您事先无法知道图像的比例,那么也许 JS 确实是您唯一的选择 - 我还没有找到替代方案


推荐阅读