如何将指定元素放置在MUI AppBar/Toolbar组件的右侧
解决方案
Material UI 的 Toolbar 组件默认采用 Flex 布局,只需新增一个占位元素撑满剩余空间即可实现 log out 按钮右对齐,完全不会改动原有左侧导航的布局逻辑。
你之前给 log out 添加的 right-0 是绝对定位属性,只有父元素设置为 position: relative 时才会生效,且绝对定位会导致元素脱离文档流,容易和其他导航项重叠,因此不推荐这种实现方式。
修改后的完整代码如下:
<main> <AppBar> <Toolbar> <Typography style={{ marginRight: 16 }} variant="h6" className="text-lg cursor-pointer" onClick={() => redirect("/")}> Home </Typography> <Typography style={{ marginRight: 16 }} variant="h6" className="text-lg cursor-pointer" onClick={() => redirect("/projects")}> Projects </Typography> <Typography style={{ marginRight: 16 }} variant="h6" className="text-lg cursor-pointer" onClick={() => redirect("/team")}> Goals </Typography> {!session && <Typography style={{ marginRight: 16 }} variant="h6" className="text-lg cursor-pointer" onClick={() => redirect("/login")}> Log in </Typography> } <!-- 新增flex占位元素,撑满剩余空间 --> <div style={{ flexGrow: 1 }} /> {session && <Typography variant="h6" className="text-lg cursor-pointer" onClick={() => signOut()}> log out </Typography> } </Toolbar> </AppBar> <Toolbar /> </main>
改动说明
- 仅新增了一行
<div style={{ flexGrow: 1 }} />代码,该元素会自动占据 Toolbar 内的所有剩余横向空间,将后续的log out按钮挤到最右侧 - 移除了
log out按钮上无效的right-0类,避免样式冲突
内容的提问来源于stack exchange,提问作者Pro Poop
相关产品推荐
相关产品推荐

