缩小一行图像以适合容器高度并保持宽高比

时间:2020-08-03 03:26:15

标签: html css flexbox

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

Here's a fiddle与目前为止的情况相同。我使用flexbox和object-fit:缩小比例来解决这个问题。该行图像为灰色,位于div中,背景为绿色。它们目前根本不缩放,但是至少在垂直和水平方向上居中,就像我希望的那样。这是我想要实现的效果的beforeafter图像(很抱歉,图像中的绿色背景变为黄色)。代码段下方的其他详细信息,但这是对基本问题的总结。

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容器在这里可以工作;似乎可以与主图像配合使用,但是辅助图像无法缩放。

此外,我知道,即使我当前的方法可行,the object-fit: scale-down strategy would leave behind some unwanted "padding"也会在次要图像之间形成可视空间。我感觉最终可能需要一种非常不同的方法来获得想要的效果,因为我希望图像彼此相邻放置而周围没有多余的空间。此外,当浏览器变得非常薄时,容器本身似乎也有问题,因为会出现滚动条,但始终应为90vh。

谢谢大家的投入!

1 个答案:

答案 0 :(得分:0)

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

此解决方案保留了我在问题中提到的有关使用object-fit: scale-down(或cover)时在图像周围创建的其他“填充”的问题。因此,这意味着我将asking another question about that topic!