flex布局中子项目尺寸不受flex-shrink限制的问题解决

来自:网络
时间:2022-05-10
阅读:

预期是写一个如下所示的布局内容:

flex布局中子项目尺寸不受flex-shrink限制的问题解决

即有一个固定高度的外部容器,顶部的header已知高度,在header占据了固定高度后,剩下的都分给body部分。因此采用flex布局,header设置flex-shrink为0,不自动收缩,body则flex-shrink为1,使其高度压缩为剩余高度。这个操作看起来挺符合直觉的。
然后在上述的body中有个content-wrapper内容块,设置height: 100%以及overflow: auto来让他高度占满父容器并且内容过多时生成滚动条。

demo代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>测试pre标签</title>
        <style>
            * {
                padding: 0;
                margin: 0;
            }
            html, body {
                height: 100%;
            }

            .container {
                width: 800px;
                height: 500px;
                display: flex;
                flex-direction: column;
            }
            .header {
                height: 100px;
                background-color: rgb(226, 110, 110);
                flex-shrink: 0;
            }
            .body {
                flex-shrink: 1;
                background-color: rgb(146, 146, 223);
            }

            .content-wrapper {
                height: 100%;
                overflow: auto;
            }
        </style>
    </head>
<body>

    <div class="container">
        <div class="header">Header</div>
        <div class="body">
            <div class="content-wrapper">
                <div style="height: 1000px">很多很多的内容</div>
            </div>
        </div>
    </div>

</body>
</html>

但最终效果确实如此:

flex布局中子项目尺寸不受flex-shrink限制的问题解决

很明显body的高度并没有被限制,实际的高度是子元素的内容高度。

So why? 用搜索引擎搜了许久没找到理想的答案,这种问题确实也很难以表述。我现在真正想知道的是:为什么我给flex布局中的子项目设置了flex-shrink: 1,但它却没按我预期的表现呢。网络上相关的资料都仅仅告知如使用的,对于我想知道的,最适合的资料应该是翻flex这块的实现标准。

依据https://www.w3.org/TR/css-flexbox-1/一节中的描述,首先是这么句话:

Note: The auto keyword, representing an automatic minimum size, is the new initial value of the min-width and min-height properties.

可知弹性项目的min-widthmin-height的默认值是auto,并不同于其他布局中的情况(默认为0)。

再往下来看:

To provide a more reasonable default minimum size for flex items, the used value of a main axis automatic minimum size on a flex item that is not a scroll container is a content-based minimum size; for scroll containers the automatic minimum size is zero, as usual.

这段话描述了在主轴方向上,上述的auto值应该如何计算弹性项目的宽/高度(我的例子中是flex-direction: column,因此主轴为垂直方向,关注点是min-height)。由上可知,对于弹性项目如果其是非滚动容器,min-height值为内容高度;反之则是0。

综上,demo中的问题,修改方法之一就是,将div.body变为滚动容器,即设置overflowscrollauto或者hidden(没错hidden属性也是,因为hidden只是隐藏溢出的内容不提供滚动条,但仍然可以通过js控制里边的内容来达到滚动效果,所以该情况也是滚动容器)。另一种方式是我们可以直接覆盖min-height的默认值,即显示设置min-height: 0 也能达到目的。

返回顶部
顶部