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

Material UI左侧固定右侧滚动布局失效问题求助

解决Material UI左侧固定、右侧可滚动布局问题

问题根源

你当前代码的问题在于:

  • position: fixed 会让左侧Box脱离文档流,Stack的row布局无法正确分配右侧Box的位置,导致右侧内容要么被左侧覆盖,要么布局错乱
  • 右侧Box未设置明确高度,overflow: scroll 不会生效——元素高度会随内容自适应,不会触发滚动

修复方案

以下是两种可行的实现方式:

方案一:使用Grid组件(推荐)

Grid的布局逻辑更适配这种分栏场景,配合粘性定位可轻松实现需求:

import { Grid, Box } from '@mui/material';

<Grid container style={{ height: '100vh' }}>
  {/* 左侧固定栏 */}
  <Grid item xs={3} sx={{ position: 'sticky', top: 0, height: '100vh' }}>
    Left-side box content
  </Grid>
  {/* 右侧滚动栏 */}
  <Grid item xs={9} sx={{ overflowY: 'auto', height: '100vh' }}>
    {/* 测试用长内容 */}
    {Array.from({ length: 50 }).map((_, idx) => (
      <div key={idx}>Right-side box content - {idx + 1}</div>
    ))}
  </Grid>
</Grid>

核心说明:

  • height: '100vh' 让容器占满视口高度,为滚动区域提供明确的高度限制
  • position: 'sticky' 替代fixed,既保持左侧固定,又不脱离Grid的文档流,避免布局冲突
  • overflowY: 'auto' 仅在内容超出时显示滚动条,比强制scroll更友好

方案二:调整Stack和Box样式(保留原组件结构)

如果坚持使用Stack,需手动处理右侧Box的偏移和高度:

import { Stack, Box } from '@mui/material';

<Stack direction="row" style={{ height: '100vh' }}>
  <Box sx={{ width: '25%', position: 'fixed', height: '100vh' }}>
    Left-side box content
  </Box>
  <Box sx={{ overflowY: 'auto', width: '75%', marginLeft: '25%', height: '100vh' }}>
    {/* 测试用长内容 */}
    {Array.from({ length: 50 }).map((_, idx) => (
      <div key={idx}>Right-side box content - {idx + 1}</div>
    ))}
  </Box>
</Stack>

核心说明:

  • 给右侧Box添加marginLeft: '25%',避免被左侧fixed元素覆盖
  • 同样设置height: '100vh'确保滚动区域有高度边界
  • overflowY: 'auto'控制垂直方向的滚动行为

关键注意事项

  • 滚动区域必须设置明确的高度限制,否则overflow属性无法触发滚动效果
  • 优先使用position: sticky替代fixed,能减少布局偏移的手动处理成本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:56:46