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

如何让Div适配屏幕剩余高度,内容溢出时显示滚动条

如何让Div自适应剩余高度并在内容溢出时显示滚动条?

你当前的布局已经基于Tailwind实现了基础的flex垂直布局,只需给第三个Div添加滚动相关样式即可满足需求:

原HTML结构:

<body class="flex">
    <div class="h-screen w-48">navbar sticking to the left covering entire height with a fixed width.</div>
    <div class="h-screen flex-1 flex flex-col">
        <div class="w-full h-20">header containing heading of the page</div>
        <div class="w-full flex-1"> <!-- covering remaining height(3rd div) -->
            <ul>
                <li>Item1</li>
                <li>Item2</li>
                <li>Item3</li>
                <li>Item4</li>
                ...many more items
            </ul>
        </div>
    </div>
</body>

解决方案

你已经通过flex flex-col和flex-1让第三个Div占据了父容器的剩余高度(父容器为h-screen,减去header的固定高度h-20),只需给第三个Div添加overflow-y-auto类,就能在内容超出容器高度时自动显示垂直滚动条:

修改后的代码:

<body class="flex">
    <div class="h-screen w-48">navbar sticking to the left covering entire height with a fixed width.</div>
    <div class="h-screen flex-1 flex flex-col">
        <div class="w-full h-20">header containing heading of the page</div>
        <div class="w-full flex-1 overflow-y-auto"> <!-- 自适应剩余高度,内容溢出时显示滚动条 -->
            <ul>
                <li>Item1</li>
                <li>Item2</li>
                <li>Item3</li>
                <li>Item4</li>
                ...many more items
            </ul>
        </div>
    </div>
</body>

原理说明

  • flex-1会让容器自动填充父级flex布局中的剩余空间,无论屏幕尺寸如何,都能精准占据header下方到屏幕底部的区域
  • overflow-y-auto会在容器内容高度超过自身高度时自动显示垂直滚动条,内容未超出时则隐藏滚动条,避免多余UI元素

这种方式比设置max-height更灵活,它通过动态计算可用空间实现适配,完美兼容不同尺寸的屏幕。

内容的提问来源于stack exchange,提问作者Prashant Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:12:18