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

MUI Modal内Div内容溢出时无法滚动的问题求助

购物车模态框内容无法滚动的解决方案

问题分析

当前模态框容器仅设置了minHeight: "500px",未限制最大高度,导致商品数量增多时容器被内容无限撑开,超出视口的部分被Modal默认定位隐藏;同时overflowY: scroll因容器无明确高度限制无法生效。此外代码存在一处语法错误,会影响样式渲染。

修复步骤

  • 添加最大高度限制:给模态框内容容器设置基于视口高度的maxHeight,确保容器不超出屏幕范围,示例:maxHeight: "calc(100vh - 40px)"(40px为上下边距,可按需调整)
  • 修复语法错误:Card组件sx属性中height: "200px,缺少闭合引号,应改为height: "200px"
  • 保留overflowY设置:确保容器overflowY: "scroll"属性正常生效

修改后的代码

<Modal
  open={open}
  onClose={handleClose}
  aria-labelledby="modal-modal-title"
  aria-describedby="modal-modal-description"
>
  <div
    style={{
      minHeight: "500px",
      maxHeight: "calc(100vh - 40px)", // 添加最大高度限制
      width: "500px",
      backgroundColor: "gray",
      gap: "10px",
      display: "flex",
      flexDirection: "column",
      overflowY: "scroll",
      margin: "20px auto", // 可选:实现水平居中
      padding: "10px" // 可选:避免内容贴边
    }}
  >
    {cart.map((displate) => {
      return (
        <Card
          key={displate.id} // 必须添加唯一key属性,消除React警告
          sx={{
            height: "200px", // 修复引号缺失问题
            display: "flex",
            padding: "10px",
            gap: "10px",
            backgroundColor: "black",
            margin: "10px",
          }}
        >
          <div
            style={{
              backgroundImage: `url(${displate.img})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              height: "150px",
              width: "120px",
            }}
          ></div>
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              justifyContent: "center",
              color: "white",
            }}
          >
            <Typography>Name: {displate.name}</Typography>
            <Typography>Size: {displate.size}</Typography>
            <Typography>Finish: {displate.finish}</Typography>
            <Typography>Frame: {displate.frame}</Typography>
            <Typography>Quantity: {displate.quantity}</Typography>
          </div>
        </Card>
      );
    })}
  </div>
</Modal>

额外提示

  • 若需隐藏滚动条,可给容器添加scrollbarWidth: "none"(适配Firefox),同时添加CSS伪类样式::-webkit-scrollbar { display: none; }(适配Chrome/Safari)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:20:32