在固定高度的容器中调整图像大小

Resize image in container with fixed height

所以基本上我想要实现的是在页面上以条带形式出现的图像(具有固定高度)。现在,如果图像太宽而无法完全容纳,我想用 "overflow: hidden" 剪掉边缘并将其居中。我设法做到了,但现在我失败了:我不希望图像太窄时被拉伸,但我希望它溢出包含 div.[= 的顶部12=]

Here 你可以看到一个例子:当你滚动到底部时你可以看到 3 张图片,我想复制这些图片在视口水平宽度为 1200px 到 1800px 之间的行为方式。


这是我目前的基本标记:

<div class="piccontainer">
    <img src="picture.jpg" class="picture"/>
</div>

.piccontainer {
    display: flex;
    justify-content: center;
    overflow: hidden;
    min-height: 20vw;
    position: relative;
}
.picture {
    height: 100%
}

我尝试了几个 jQuery 插件,但都没有产生预期的结果,而且我无法修改 CSS 来产生我需要的结果。我非常心烦意乱,因此非常感谢任何帮助!

提前致谢!

更优雅的解决方案是在 div 上使用背景图像。

例如:

.piccontainer {
  background-image:url('/bg.png');
  background-repeat:no-repeat;
  background-size:cover;
  background-position:center;
  height: 100vh;
}

插入图片需要100%吗?您是否考虑使用图像作为背景,如:

.anyElement{
   background-image: url("yourimage.jpeg");
   background-attachment: fixed;
   background-repeat:no-repeat;
   background-size:contain;
   background-position:center;
}

您可能想尝试将图像用作背景图像,然后在图像上使用 background-size:cover; 属性。

这样你就可以修复你的包含元素并且你的图像将填充容器。

.piccontainer {
    display: flex;
    justify-content: center;
    overflow: hidden;
    min-height: 20vw;
    position: relative;
    background-image:url(picture.jpg);
    background-size:cover;
    background-position:center center;
}

参考:Background size on MDN