【发布时间】:2019-09-10 13:07:20
【问题描述】:
我正在尝试获取可变数量的方形图像来填充父容器。我需要图像的大小响应增大或缩小,以确保它们都适合,但永远不要横向和扩展超出父容器的大小。图像比例也需要在不裁剪的情况下保留。
我正在尝试使用嵌套的弹性框来实现这一点。 .outer-flex-container 正在按预期工作,所有内容都沿水平轴缩小/增长,同时保持纵横比。
使用.inner-flex-container,我试图获得相同的结果,但沿垂直轴(flex-flow: column)。但是,当您缩小容器大小时,您会得到不会缩小(或扭曲纵横比)的图像。
我已经阅读了大量关于使用min-height: 0 覆盖默认min-height: auto 的帖子,但这似乎并不能解决我的问题。
为什么.inner-flex-container 没有缩小到容器的大小?有没有比 flexbox 更好的方法来实现这一点?
.outer-flex-container {
display: flex;
flex-flow: row nowrap;
border: 1px solid red;
width: 900px;
height: 500px;
}
.outer-flex-container:hover {
width: 500px;
height: 100px;
}
.outer-flex-child {
flex: 0 1 auto;
min-height: 0;
min-width: 0;
}
.inner-flex-container {
display: flex;
flex-flow: column nowrap;
border: 1px solid grey;
min-height: 0;
min-width: 0;
/* max-height: 100%; <-- Distorts aspect ratio */
/* max-width: 100%; <-- Distorts aspect ratio */
}
.inner-flex-child {
flex: 0 1 auto;
min-height: 0;
min-width: 0;
max-height: 100%;
max-width: 100%;
opacity: 0.5;
}
<div class="outer-flex-container">
<div class="outer-flex-child">
<div class="inner-flex-container">
<img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
</div>
</div>
<div class="outer-flex-child">
<div class="inner-flex-container">
<img class="inner-flex-child" src='https://i.stack.imgur.com/QH01k.png' />
</div>
</div>
</div>
【问题讨论】:
-
这就是你要找的东西:jsfiddle.net/tj27rLw1
-
是的,这看起来确实是我想要的。那么,看起来我需要使 .outer-flex-child 成为一个 .inner-flex-container 作为其子弹性项目的弹性容器?或者换句话说,当我需要 3 层时,我错误地只有 2 层嵌套? (感谢您的帮助)
-
已在下面添加了答案并附有解释,谢谢:)