如何为Material-UI AppBar添加类似MUI-CSS的左右垂直分隔线?
如何在Material-UI AppBar中添加垂直分隔线
你遇到的问题其实是Flex布局的特性导致的——Toolbar默认使用flex布局,子元素默认的align-items是center,所以直接给div设置height:100%不会生效,它只会根据内容高度渲染,无法自动拉伸到Toolbar的高度。下面给你几种可行的解决方案:
方法1:使用Material-UI的Box组件(推荐)
Box组件可以轻松处理布局样式,只需设置边框和拉伸属性即可:
<AppBar position="static" color="default"> <Toolbar> <Typography type="title" color="inherit"> Title </Typography> <Box sx={{ alignSelf: 'stretch', borderLeft: '1px solid #ff0000', mx: 2 // 左右间距,可选 }} /> <Typography type="title" color="inherit"> Title 2 </Typography> </Toolbar> </AppBar>
alignSelf: 'stretch'会让Box组件拉伸至Toolbar的高度,再通过borderLeft设置垂直分隔线的样式,mx可以调整分隔线和两侧元素的间距。
方法2:自定义div样式
如果你不想用Box组件,也可以直接修改div的样式,核心是设置alignSelf: 'stretch'和正确的边框:
<AppBar position="static" color="default"> <Toolbar> <Typography type="title" color="inherit"> Title </Typography> <div style={{ alignSelf: 'stretch', borderLeft: '1px solid #ff0000', margin: '0 16px' // 可选,调整间距 }} /> <Typography type="title" color="inherit"> Title 2 </Typography> </Toolbar> </AppBar>
这里去掉了原来的border: solid #ff0000(会给div加四面边框),换成borderLeft只显示左侧边框作为分隔线,同时alignSelf: 'stretch'确保div高度匹配Toolbar。
方法3:使用垂直方向的Divider组件
Material-UI的Divider组件支持垂直方向,只需设置orientation="vertical"并调整样式:
import Divider from '@material-ui/core/Divider'; <AppBar position="static" color="default"> <Toolbar> <Typography type="title" color="inherit"> Title </Typography> <Divider orientation="vertical" sx={{ height: 'auto', alignSelf: 'stretch', mx: 2 }} /> <Typography type="title" color="inherit"> Title 2 </Typography> </Toolbar> </AppBar>
这种方法更符合Material-UI的组件化风格,orientation="vertical"将Divider转为垂直方向,alignSelf: 'stretch'保证高度填充Toolbar。
内容的提问来源于stack exchange,提问作者Ozawa Tomohiko
相关产品推荐
相关产品推荐

