Material-UI的AppBar固定顶部后内容被遮挡怎么办?

UX文明 阅读 18

我在用Material-UI的AppBar做导航栏时,设置position:fixed后虽然能固定顶部,但页面内容还是被导航栏遮住了。试过给内容区域加margin-top=”64px”,但滚动时会出现错位,有没有更好的解决办法?


<AppBar position="fixed" style={{ backgroundColor: '#3f51b5' }}>
  <Toolbar>
    <Typography variant="h6">我的网站</Typography>
  </Toolbar>
</AppBar>
<div style={{ marginTop: '64px', padding: '20px' }}>
  这里的内容被导航栏遮挡了...
</div>

发现当页面有滚动条时,margin-top会导致内容在滚动时上下跳动,可能是计算高度的方式有问题,但不知道该怎么调整样式才能让内容始终在AppBar下方显示

我来解答 赞 3 收藏
二维码
手机扫码查看
2 条解答
UX-亚捷
UX-亚捷 Lv1
改一下就行,这个问题太常见了。你用 fixed 定位的 AppBar 会脱离文档流,后面的内容自然就往上顶被遮住了。

别直接写死 margin-top,因为不同屏幕、不同分辨率下 AppBar 高度可能不一样(比如移动端折叠后高度变小)。正确的做法是给 body 或根容器留出一个等高间距。

最简单的方案是在 AppBar 下面加一个占位元素,高度等于 AppBar 的高度:

<AppBar position="fixed">
<Toolbar>
<Typography variant="h6">我的网站</Typography>
</Toolbar>
</AppBar>
{/* 占位,防止内容被遮挡 */}


这里的内容不会再被遮挡了...



但更好的方式是动态获取 AppBar 高度,避免写死 64px:

你可以用 useRef 拿到 AppBar 实例,或者直接使用 theme.spacing 计算:

const theme = useTheme();
const appBarHeight = theme.mixins.toolbar.minHeight || 64;

return (
<>
<AppBar position="fixed">
<Toolbar><Typography variant="h6">我的网站</Typography></Toolbar>
</AppBar>
<div style={{ height: appBarHeight }} />
<main style={{ padding: '20px' }}>
内容正常显示
</main>
</>
);


这样滚动也不会跳动,因为占位元素稳定撑开了空间。记住:fixed 元素要靠外部结构留白,不是让内容自己去 margin。
点赞 2
2026-02-10 17:39
南宫诗琪
给 body 加 padding-top,而不是给内容容器加 margin-top。

body {
padding-top: 64px;
margin: 0;
}


AppBar 固定定位脱离文档流,撑开 body 才能避免滚动跳动。就这样。
点赞 6
2026-02-10 12:00