首页 > 解决方案 > 缩小一行图像以适应容器高度并保持纵横比

问题描述

我想知道如何缩小一排图像,使它们都适合一个未指定高度的 div。图像不应放大到超出其原始高度,并且必须保持其纵横比。另外,我希望包含 div 的高度限制为最高图像的本机高度。图像标签没有高度或宽度属性。

这是我到目前为止所拥有的一个小提琴。我使用 flexbox 和 object-fit: scale-down 来解决这个问题。有问题的图像行是灰色的,位于绿色背景的 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-grow 值的 flexbox 容器可以在这里工作;它似乎在某种程度上适用于主要图像,但次要图像拒绝缩放。

另外,我知道,即使我目前的方法有效,object-fit: scale-down 策略也会留下一些不需要的“填充”,这将导致次图像之间的视觉空间。我有一种感觉,最终可能需要一种非常不同的方法来获得我想要的效果,因为我希望图像彼此相邻而没有额外的空间。此外,当浏览器变得非常薄时,容器本身似乎也存在问题,因为会出现滚动条,但它应该始终为 90vh。

谢谢大家的投入!

标签: htmlcssflexbox

解决方案


为 .添加min-height: 0;规则.flex-row。我想这意味着当我问这个问题时它非常接近工作。

该解决方案保留了我在问题中提到的关于在使用object-fit: scale-down(or cover) 时围绕图像创建的额外“填充”的问题。所以,这意味着我会问另一个关于这个话题的问题!


推荐阅读