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

如何在React的MUI AppBar中垂直水平居中Logo?

解决MUI AppBar中Logo单独居中对齐的问题

要让Logo在AppBar的Toolbar中实现单独水平、垂直居中,核心是利用Toolbar的flex布局特性,调整Logo容器的样式来占据剩余空间并实现居中:

  1. 给Logo所在的Box组件添加flex: 1,让它占据Toolbar中除左侧元素外的所有剩余空间
  2. 开启flex布局并设置水平居中,同时确保垂直居中(可选,Toolbar默认已垂直居中)

修改后的关键代码片段:

<Box
  component="img"
  sx={{
    height: 32,
    flex: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center'
  }}
  alt="MyLogo"
  src={logo}
/>

完整的AppBar.tsx代码:

import * as React from 'react';
import { styled, useTheme } from '@mui/material/styles';

import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';

import logo from './../assets/images/logo_white.svg'
import Box from '@mui/material/Box';
const drawerWidth = 240;

interface AppBarProps extends MuiAppBarProps {
  open?: boolean;
}

const AppBar = styled(MuiAppBar, {
    shouldForwardProp: (prop) => prop !== "open"
  })<AppBarProps>(({ theme, open }) => ({
    transition: theme.transitions.create(["margin", "width"], {
      easing: theme.transitions.easing.sharp,
      duration: theme.transitions.duration.leavingScreen
    }),
    ...(open && {
      width: `calc(100% - ${drawerWidth}px)`,
      marginLeft: `${drawerWidth}px`,
      transition: theme.transitions.create(["margin", "width"], {
        easing: theme.transitions.easing.easeOut,
        duration: theme.transitions.duration.enteringScreen
      })
    })
  }));

export default function AppBar({ open, onDrawerOpen }:any) {
  const theme = useTheme();

  return (
    <AppBar position="fixed" style={{ background: "#002a5e" }} open={open}>
      <Toolbar>
        <IconButton
          color="inherit"
          aria-label="open drawer"
          onClick={onDrawerOpen}
          edge="start"
          sx={{ mr: 2, ...(open && { display: "none" }) }}
        >
          <MenuIcon />
        </IconButton>
        <Typography variant="h6" noWrap component="div">
          TITLE
        </Typography>

        <Box
          component="img"
          sx={{
            height: 32,
            flex: 1,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
          alt="MyLogo"
          src={logo}
        />

      </Toolbar>
    </AppBar>
  );
}

修改后,Logo会在Toolbar的剩余空间内水平居中,垂直方向保持与Toolbar内容一致的居中状态,同时左侧的菜单按钮和标题会正常显示在左侧。

内容的提问来源于stack exchange,提问作者Sandeep Thomas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:35:48