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

如何使用Tailwind CSS实现div内部滚动,侧边栏固定不跟随滚动

实现方案

你只需要调整几个类名即可达到需求,核心是控制主内容区的溢出滚动行为:

  • 给外层main容器添加overflow-hidden,彻底禁止父级触发滚动
  • 右侧主内容区把h-screen替换为h-full,继承父容器的屏幕高度即可,避免高度计算冲突
  • 右侧主内容区新增overflow-y-auto,这是实现内部滚动的核心属性,内容超出容器高度时自动出现纵向滚动条,仅在区域内部滚动
  • 可选添加overscroll-contain,避免滚动到内容边界时触发页面默认的弹性滚动效果

修改后的完整代码如下:

<main className="flex flex-row h-screen overflow-hidden">
  <div className="w-1/5 h-full flex flex-col bg-purple-50">
    ////This is the side nav
  </div>

  <div className="w-4/5 bg-gray-50 h-full overflow-y-auto overscroll-contain">
    /// this is the main content div that i need the content inside to scroll internally
    /// what i mean by this is i dont want the whole page to move when there is a lot of content 
    /// just the content inside this div
  </div>
</main>

额外说明:侧边导航原来的flex-grow可以移除,你已经明确给左右两侧设置了w-1/5和w-4/5的宽度占比,不需要额外的弹性占宽逻辑,避免出现布局错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 04:21:00