CSS:使用最大宽度和最大高度保持响应式img的纵横比

Dev*_*abc 5 html css layout responsive-design

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

问题:

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

  • max-width: 100%,这样就不会向右溢出,并且在缩小屏幕宽度时能够响应。
  • max-height: 200px,这样大图像的渲染尺寸就会减小。
  • 设置 height 和 width html 属性,以便浏览器可以预先计算所需的图像尺寸,以便在加载图像时布局不会移动/移动图像旁边/下方的元素。(以减少累积布局偏移。)
  • 图像长宽比应保持 1:1
  • 图像周围不应创建额外的边距
  • 图像应该使用纯 html img 标签呈现,而不是使用 css 背景图像
  • 图像的渲染尺寸不应大于其原始尺寸

我怎样才能用 CSS 实现这一点?

(如果 CSS 无法实现这一点,那么也许可以在 JavaScript 中实现?)

我尝试过的

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

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

(绿色文本应该位于袋熊的右侧,没有边距。但是对象拟合会导致填充/边距与原始图像的长度一起出现。)

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

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

小智 -1

如果您的问题是您的网页/网站没有响应,那么我建议您使用视口单位(例如vw宽度和高度而不是所有元素(包括边框字体大小),因为它将帮助您制作网页/网站响应式。vhpx%

它应该可以解决您的问题,但如果评论中没有让我知道,我会尽力帮助您。