React+MUI中Typography组件居中失效,请求技术支援
MUI Typography组件居中失效问题解决
我尝试使用textAlign与align属性使MUI的Typography组件居中,但均未生效,相关代码及页面效果如下:
相关代码
import React, {useState} from 'react' import logo from '../../images/logo.svg' import { Typography, Toolbar, AppBar } from '@mui/material' import AccountCircleIcon from "@mui/icons-material/AccountCircle" import { styled } from '@mui/material/styles' const NavBar = () => { const StyledToolbar = styled(Toolbar)({ display: "flex", alignItems: "center", justifyContent: "space-between" }); const Logo = styled("img")({ width: "12rem", height: "auto", }); const StyledAppBar = styled(AppBar)({ position: "sticky", backgroundColor: "#EDEDED", }); return ( <StyledAppBar> <StyledToolbar> <Logo src={logo} alt="quizy" /> <Typography variant="h5" color="black" align='center'> Question </Typography> <AccountCircleIcon style={{ color: "black" }} /> </StyledToolbar> </StyledAppBar> ); }
(注:补充了原代码中缺失的Toolbar、AppBar导入和styled导入)
页面效果

问题原因
你的StyledToolbar设置了justifyContent: "space-between",这会让三个子元素(Logo、Typography、图标)分别对齐容器的左、中、右,但Typography默认宽度仅包裹内容,所以即使设置align='center'也只是让文本在自身内容范围内居中,无法占据Toolbar中间的全部空间,视觉上看起来没有居中。
解决方法
方法一:给Typography添加flex占比
让Typography占据Toolbar的剩余空间,这样align='center'就能让文本在该空间内水平居中:
<Typography variant="h5" color="black" align='center' sx={{ flex: 1 }}> Question </Typography>
方法二:使用styled自定义Typography样式
如果习惯用styled方式,可以定义带flex属性的Typography:
const CenteredTypography = styled(Typography)({ flex: 1, textAlign: 'center' }); // 替换原组件 <CenteredTypography variant="h5" color="black"> Question </CenteredTypography>
内容的提问来源于stack exchange,提问作者Thành Phạm
相关产品推荐
相关产品推荐

