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

React实现占满可用高度的可滚动div解决方案咨询

问题描述

我正在为我的应用制作布局,目标是让.main__content元素占满所有可用高度,当内容超出时自动滚动。我尝试将段落包裹到另一个div中,但没有效果。请问有什么方法可以实现这个需求?

解决方案

核心问题在于flex子元素的默认最小高度限制以及grid布局的行高计算方式,修改以下两点即可解决:

  1. 用1fr替代手动计算的行高:将.workspace的grid-template-rows改为48px 1fr 24px,让grid自动分配中间区域的剩余高度,比calc(100% - 72px)更可靠且适配性更强。
  2. 给.main__content添加min-height: 0:flex子元素默认min-height: auto,会跟随内容高度拉伸,导致无法触发滚动;设置min-height: 0后,它会遵守flex容器的高度分配,内容超出时自动显示滚动条。
修改后的代码

styles.scss

.workspace {
  width: 100vw;
  height: 100vh;

  display: grid;
  // 改用1fr自动分配剩余高度
  grid-template-rows: 48px 1fr 24px;

  .header {
    background: coral;
  }

  .content {
    display: grid;
    grid-template-columns: 48px 300px calc(100vw - 348px);
    
    background: red;

    .menu {
      background: darkslateblue;
    }

    .sidebar {
      background: darkslategray;
    }

    .main {
      height: 100%;
      display: flex;
      flex-direction: column;

      .tabs {
        height: 48px;
        background: cyan;
      }

      &__content {
        flex-grow: 1;
        background: rebeccapurple;
        display: flex;
        flex-direction: column;
        overflow-y: auto;
        // 添加该属性打破flex子元素的最小高度限制
        min-height: 0;
      }
    }
  }

  .footer {
    background: yellowgreen;
  }
}

App.tsx(无需修改)

function App() {
  const items = new Array(50).fill(null);

  return (
    <div className={style.workspace}>
      <div className={style.header}>header</div>

      <div className={style.content}>
        <div className={style.menu}>menu</div>
        <div className={style.sidebar}>sidebar</div>

        <div className={style.main}>
          <div className={style.tabs}>tabs</div>
          <div className={style.main__content}>
            {items.map((_, index) => (
              <p key={index}>line</p>
            ))}
          </div>
        </div>
      </div>

      <div className={style.footer}>footer</div>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:50:11