缩小一行图像以适应容器高度并保持纵横比



我想知道如何缩小一行图像,使它们都适合一个未指定高度的div。图像的比例永远不应超过其原始高度,并且必须保持其纵横比。此外,我希望包含div的高度限制为最高图像的本地高度。图像标记没有高度或宽度属性。

这是我迄今为止拥有的一把小提琴。我使用flexbox和对象拟合来处理这个问题:缩小比例。有问题的图像行是灰色的,位于绿色背景的div中。它们目前根本不按比例缩放,但它们至少以我希望的方式垂直和水平居中。以下是我想要实现的效果的前后图像(很抱歉将图像中的绿色背景切换为黄色(。代码片段下面的其他详细信息,但关于总结了基本问题。

body {
font-family: arial;
font-size: 26px;
text-align: center;
color: black;
background-color: white;
}
.smallhint {
font-size: 16px;
color: #8c8c8c;
}
img {
padding: 0;
margin: 0;
font-size: 0;
display: block;
object-fit: scale-down;
min-height: 0;
}
.flex-column {
display: flex;
flex-direction: column;
padding: 0px;
margin: 0px;
height: 90vh;
flex-grow: 0;
min-width: 0;
min-height: 0;
}
.flex-row {
display: flex;
flex-direction: row;
flex: 0 1.5 auto;
justify-content: center;
align-items: center;
background-color: green;
}
.context {
display: flex;
flex-direction: column;
max-height: 100%;
background-color: blue;
}
.primary {
position: relative;
z-index: 0;
right: 0;
bottom: 0;
padding: 0;
font-size: 0;
min-height: 0;
align-items: end;
background-color: orange;
}
.primary img {
margin-left: auto;
margin-right: auto;
border-style: solid;
border-width: 3px;
border-color: black;
height: calc(100% - 2*3px);
}
.mask {
position: absolute;
z-index: 1;
top: 0;
right: 0;
width: 100%;
height: 100%;
font-size: 0;
}
.nonimage {
padding-top: 5px;
display: inline;
background-color: pink;
}
<div class="flex-column">
<div class="primary">
<img src="https://via.placeholder.com/200">
<div class="mask">
<img src="https://via.placeholder.com/200/FF000">
</div>
</div>
<div class="flex-row">
<div class="context">
<img src="https://via.placeholder.com/75x150">
</div>
<div class="context">
<img src="https://via.placeholder.com/150x75">
</div>
</div>
<div class="nonimage">
<div class="smallhint">Some Text<br>Other Text</div>
</div>
</div>

我正在开发一个CSS风格的(固定高度(界面,可能会问一系列问题。我不擅长CSS,所以我对与我失败的尝试截然不同的方法持开放态度!

顶部是单中心图像("主图像"(,下面是一行中的另外两个图像("次图像"(;下面是一些文本。最终,我希望两组图像都能对浏览器的高度和宽度的变化做出响应。然而,当浏览器太短,无法包含原生尺寸的所有内容时,我更愿意缩小次映像而不是主映像。为此,具有各种flex增长值的flexbox容器似乎可以在这里工作;它似乎在一定程度上适用于主映像,但次映像拒绝缩放。

此外,我知道,即使我目前的方法奏效了,对象匹配:缩小策略也会留下一些不想要的";填充";这将导致二次图像之间的视觉空间。我有一种感觉,最终可能需要一种非常不同的方法来获得我想要的效果,因为我希望图像彼此相邻,周围没有额外的空间。此外,当浏览器变得非常薄时,容器本身似乎也有问题,因为出现了滚动条,但它应该始终是90vh。

感谢大家的投入!

.flex-row添加min-height: 0;规则。我想这意味着当我问这个问题的时候,它已经很接近工作了。

该解决方案保留了我在关于附加";填充";当使用object-fit: scale-down(或cover(时在图像周围创建。所以,这意味着我会再问一个关于这个话题的问题!

最新更新