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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:45:36