html - CSS:在最大宽度和最大高度的响应式图像中保持纵横比
问题描述
(stackoverflow 上已经提出了类似的问题,但是这个问题有更多的限制,例如特定的最大宽度、最大高度、所需的特定高度和宽度,以及没有布局移位。)
问题:
我想要一个具有以下约束的响应式图像:
- max-width: 100%,这样它就不会向右溢出,并且在减小屏幕宽度时它是响应式的。
- max-height: 200px,这样大图像的渲染尺寸就会减小。
- height 和 width html 属性设置,以便浏览器可以预先计算所需的图像尺寸,以便在图像加载时布局不会在图像旁边/下方移动/移动元素。(以减少累积布局偏移。)
- 图像纵横比应保持 1:1
- 不应在图像周围创建额外的边距
- 应该使用纯 html img 标签呈现图像,而不是使用 css background-images
- 图像的渲染尺寸不应大于其原始尺寸
如何使用 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 解决此问题?
解决方案
多年来我一直在为此苦苦挣扎,但是就在今天,当您知道图像的纵横比时,我想出了一种方法,希望对您有所帮助:
首先在与图像比例对应的元素中定义一个--img-ratio
CSS 自定义属性。img
height / 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 确实是您唯一的选择 - 我还没有找到替代方案
推荐阅读
- docker - 访问我自己的域的 Linuxserver/Wireguard 问题
- javascript - 同一网络上的 2 个设备的套接字无法正常工作
- python - 如何获取 zendesk 票证中关联的所有事件
- javascript - 如何从提供的文件路径中检索文件对象
- python - 多处理转换大约需要 25 秒.. 为什么?
- php - 在 Laravel 中使用 Eloquent 创建 count() 和 groupBy
- php - 错误:在第 80 行调用 src\addons\EWR\Rio\Api\YouTube.php 中未定义的方法 GuzzleHttp\Psr7\Response::json()
- c++ - 无法使用 ms-iot/husky 从 Windows 中的源代码构建 husky
- c# - NSwag 和扩展代码 - 如何确保它放在文件的开头?
- python-3.x - 查找特定单元格满足特定正则表达式的数据框行