我正在尝试将图像垂直放入具有特定高度的 flex 容器中。
flex-direction
是 column
,图像包含在 flex-item
中,flex-basis: 100 %
.
此外,图像的max-height
为100%
。
正如您在示例中看到的,图像不适合红色容器。
#container {
background-color: red;
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 200px;
width: 320px;
justify-content: space-between;
}
#container > * {
padding: 5px;
}
#img {
flex: 0 1 100%;
/* height: 100%; */
}
img {
max-height: 100%;
max-width: 100%;
}
<div id="container">
<div id="img">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=img&w=340&h=500">
</div>
<div>
Something else
</div>
</div>
根据规范,图像不应该收缩以垂直适合 flex 容器吗?
我发现的解决方法是将#img
的height
设置为100%
,但我感觉这不是这样的应该这样做。
作为补充说明,如果我将 flex-direction: row
设置为容器,它会水平适合图像(这是我期望的行为)。
最佳答案
您写道:
The workaround I found is to set the height of
#img
to 100%, but I have the sensation that it's not the way it should be done.
事实上,这是应该这样做的。该规范的主要实现要求在子级上使用百分比高度时将 height
属性应用于父级。 (尽管这正在慢慢发展。请参阅下面我的第二个引用文献。)
引用文献:
关于html - 如何在方向: column的 flex 容器中垂直放置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37004526/