【发布时间】:2021-05-17 02:52:03
【问题描述】:
我有一个 flex 容器,为了简单起见,它具有 300 像素的固定高度(实际上它具有灵活的高度)。在这个容器中还有其他几个容器,例如标题和文本。
其中一个容器包含一张图片。这个容器应该增长到填满剩余的高度。
理论上,使用 flexbox,这个解决方案是直截了当的(如果没有它也可以工作的图像):
<html><body>
<div style="display: flex; flex-flow: column; height: 300px;">
<div style="background: green;">HEADER</div>
<div style="background: red;">CAPTION</div>
<div style="background: blue;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
<div style="background: yellow; flex: 1">
<span>flexible image container that fills the remaining space</span>
</div>
<div style="background: orange;">
<button>ACTION</button>
</div>
</div>
</body></html>
但是,一旦我添加了图像,布局就会中断,并且图像会占用其固有高度的 100%(在本示例中:500px)。
<html><body>
<div style="display: flex; flex-flow: column; height: 300px;">
<div style="background: green;">HEADER</div>
<div style="background: red;">CAPTION</div>
<div style="background: blue;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
<div style="background: yellow; flex: 1">
<img src="https://via.placeholder.com/100x500" >
</div>
<div style="background: orange;">
<button>ACTION</button>
</div>
</div>
</body></html>
如何告诉这张图片不要超过 flexbox 计算的剩余高度?遗憾的是,我不能只给每个元素一个固定的高度,因为在这种情况下每个容器或多或少都可能有任意内容。
【问题讨论】:
-
@Martin 我也发现了这个问题,但无法使答案符合我的问题。至少没有任何建议对图像高度有任何影响。
-
@MichaelBenjamin Welp,我不记得它是什么,但由于某种原因,我尝试过的方法对我不起作用。感谢您指出此解决方案,因为它比公认的解决方案简单得多。