You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网格内Div无法继承父元素最大高度的布局问题

解决右下角区域独立滚动的问题

我明白你的困扰——想要让蓝色的.page-content-area单独滚动,结果整个页面都出现了滚动条,临时固定header高度的方案又不够灵活。咱们来一步步解决这个问题:

问题根源

你的.app-container用了grid-template-rows: auto 1fr来分配header和内容区域的高度,但Grid布局有个默认行为:当子元素的内容超出轨道分配的空间时,会自动拉伸轨道的高度(也就是1fr的那一行会被撑开)。这就导致.page-with-left-area的高度超过了100vh,整个页面自然就出现了滚动条。

解决方案

只需要给.page-with-left-area添加min-height: 0,就能打破Grid的默认拉伸行为,让它严格遵守父级分配的高度。这样.page-content-area的height: 100%就能正确对应父级的剩余空间,overflow: auto也会在内容超出时生效。

修改后的完整代码如下:

<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>PageContainer</title>
    <style>
        * { box-sizing: border-box; }
        body { padding: 0; margin: 0; }

        .app-container {
            width: 100vw;
            height: 100vh;
            display: grid;
            grid-template-rows: auto 1fr; /* 保留原布局,无需固定header高度 */
        }

        .page-with-left-area {
            width: 100%;
            height: 100%;
            max-width: 100%;
            max-height: 100%;
            display: grid;
            grid-template-columns: 18rem 1fr;
            background-color: red;
            min-height: 0; /* 关键修改:打破Grid轨道拉伸 */
        }

        .page-content-area {
            width: 100%;
            height: 100%;
            max-width: 100%;
            max-height: 100%;
            padding: 0.5rem;
            padding-bottom: 1.2rem;
            background-color: blue;
            border: 3px solid black;
            overflow: auto; /* 保持滚动设置 */
        }

        .test-header {
            width: 100%;
            height: 8.5rem;
            background-color: green;
        }

        .test-page-content {
            width: 100%;
            height: 100%;
            min-width: 40rem;
            min-height: 40rem;
            background-color: yellow;
            border: 3px solid red;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="test-header"></div>
        <div class="page-with-left-area">
            <div></div>
            <div class="page-content-area">
                <div class="test-page-content"></div>
            </div>
        </div>
    </div>
</body>
</html>

效果验证

修改后,.page-with-left-area会被严格限制在app-container分配的剩余高度里,当黄色的.test-page-content内容超出时,只有蓝色的.page-content-area会显示滚动条,整个页面不会出现滚动,同时header的高度依然可以灵活调整,不需要固定数值。

内容的提问来源于stack exchange,提问作者Marcel Wolterbeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:47:56