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

网格容器中设置overflow-y:auto的子元素无法滚动问题求助

解决滚动容器占剩余空间并实现滚动的问题

你的问题出在:带overflow-y:auto的flex容器没有被父级高度约束,它会跟着内部内容撑开,所以不会触发滚动。只要给这个容器加上h-full,让它继承父级网格分配的剩余空间高度,就能实现预期效果。

修改后的代码:

<script src="https://cdn.tailwindcss.com"></script>

<div class="h-screen grid grid-rows-[auto,1fr]">
  <div class="bg-slate-300 h-24 flex items-center px-4">
    <h1 class="text-3xl">Navbar</h1>
  </div>
  <div class="p-4 gap-2 grid grid-rows-[auto,1fr]">
    <h1 class="text-3xl">Title</h1>
    <div class="gap-4 grid grid-rows-[auto,1fr]">
      <div class="flex">
        <button class="btn border rounded p-2">Button</button>
      </div>
      <!-- 添加h-full约束高度 -->
      <div class="overflow-y-auto flex flex-col gap-2 h-full">
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
        <div class="h-[200px] bg-slate-100"></div>
      </div>
    </div>
  </div>
</div>

原理:父级通过grid-rows-[auto,1fr]给滚动容器分配了剩余空间,但flex容器默认会“收缩包裹”内容,加上h-full后,它会强制占满父级分配的高度,当内部内容高度超过这个值时,overflow-y:auto就会生效,自动显示滚动条。

内容的提问来源于stack exchange,提问作者Matt Peng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:35:01