在CSS flexbox布局中,如果父块是可垂直滚动的,是否有方法将子块高度锁定为父块(滚动)高度



如果我有这样的HTML结构:

<div style="display: flex; align-items: stretch; height: 150px; overflow: auto">
<div style="background: red; width: 30px"></div>
<div style="background: yellow; flex-grow: 2; height: 200px"></div>
</div>

align-items: stretch将第一个子项的高度设置为flex元素的innerHeight,而不是其实际的可滚动高度。因此,当向下滚动时,红色背景停止在初始视口的底部。

height: 100%也有类似的问题(身高和父母的外表尺寸有关(。

可以通过引入另一个包装元素来解决这个问题,并将overflowheight样式移动到该元素,但在我的情况下,由于其他原因,这很尴尬。有没有什么方法可以让所有灵活的孩子保持相同的(全(身高而不这样做?

您可以使用flex包装,但它显然会导致包装。根据您的用例,您可能会发现也可能不会发现以其他方式解决这一问题更容易。

<div style="display: flex; flex-wrap: wrap; align-items: stretch; height: 150px; overflow: auto">
<div style="background: red; width: 30px"></div>
<div style="background: yellow; flex-grow: 2; height: 200px"></div>
</div>

这一变化的要点是,对于非换行换行符,行的高度由父元素的高度给定(在您的示例中为150px(,但对于换行换行符来说,会考虑子元素的高度(此处为200px(。

依据:https://bugzilla.mozilla.org/show_bug.cgi?id=1267060

使用CSS网格是否适合您的情况?

以下内容似乎符合您的要求:

<div style="
display: grid;
height: 150px;
overflow: auto;
grid-template-columns: min-content 1fr;
">
<div style="background: red; width: 30px">1</div>
<div style="background: yellow; height: 200px">hi</div>
</div>

最新更新