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

Tailwind CSS实现仅网格中心区域滚动的布局方案问询

解决方案

1. 调整整体布局高度,消除全局滚动

  • 给body添加h-screen overflow-hidden,固定页面高度为屏幕高度,隐藏全局滚动条,避免整体网格随滚动移动
  • 主内容区使用grid布局并设置h-full,确保其占满头部下方的剩余垂直空间

2. 固定左右区域,实现中间区域独立滚动

  • 左右侧边区域添加sticky top-0 h-full,使其固定在视口顶部且高度铺满主内容区
  • 中间区域容器添加overflow-y-auto h-full scrollbar-gutter-stable,让内部内容超出时自动显示垂直滚动条,同时避免滚动条出现/消失时的布局跳动

3. 实现全局滚动触发中间区域滚动

添加以下JS代码,捕获页面滚轮事件并同步到中间滚动区域:

const centerScroll = document.getElementById('center-scroll');
document.addEventListener('wheel', (e) => {
  if (centerScroll) {
    centerScroll.scrollTop += e.deltaY;
    e.preventDefault();
  }
}, { passive: false });

核心代码示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fixed Layout with Scrollable Center</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-screen overflow-hidden">
  <!-- 固定头部 -->
  <header class="h-16 bg-blue-500 text-white flex items-center justify-center">
    Fixed Header
  </header>

  <!-- 主内容网格布局 -->
  <div class="grid grid-cols-[200px_1fr_200px] h-full">
    <!-- 左侧固定区域 -->
    <div class="sticky top-0 h-full bg-gray-100 p-4">
      Left Fixed Area<br>
      Content remains fixed
    </div>

    <!-- 中间滚动区域 -->
    <div id="center-scroll" class="overflow-y-auto h-full scrollbar-gutter-stable p-4">
      <div class="test">
        <!-- 填充足够多测试内容触发滚动 -->
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
        Test Content<br>
      </div>
    </div>

    <!-- 右侧固定区域 -->
    <div class="sticky top-0 h-full bg-gray-100 p-4">
      Right Fixed Area<br>
      Content remains fixed
    </div>
  </div>

  <script>
    const centerScroll = document.getElementById('center-scroll');
    document.addEventListener('wheel', (e) => {
      if (centerScroll) {
        centerScroll.scrollTop += e.deltaY;
        e.preventDefault();
      }
    }, { passive: false });
  </script>
</body>
</html>

关键说明

  • sticky top-0 h-full:确保左右区域始终固定在视口顶部,且高度与主内容区一致
  • overflow-y-auto h-full:限制中间区域的滚动范围仅为自身容器,不影响其他区域
  • 滚轮事件监听:将页面任意位置的滚动操作映射到中间区域,同时阻止全局滚动行为,保证交互一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:37:18