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

React Material UI:如何将内容居中到页面中间

如何将MUI按钮居中到页面中间

下面提供几种简单可行的实现方案:

方案1:原生Flexbox内联样式

给按钮的父容器设置Flex布局,让按钮同时实现水平和垂直居中:

import { Button } from '@mui/material';

function App() {
  return (
    <div style={{ 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center', 
      minHeight: '100vh' 
    }}>
      <Button variant="contained">Hello World</Button>
    </div>
  );
}

export default App;
  • minHeight: '100vh':让父容器占满整个浏览器视口高度,保证按钮垂直方向居中
  • justifyContent: 'center':控制按钮水平居中
  • alignItems: 'center':控制按钮垂直居中

方案2:使用MUI Box组件(推荐)

如果你的项目基于MUI生态,用Box组件的sx属性来设置布局更贴合项目习惯:

import { Button, Box } from '@mui/material';

function App() {
  return (
    <Box 
      sx={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '100vh' 
      }}
    >
      <Button variant="contained">Hello World</Button>
    </Box>
  );
}

export default App;

sx是MUI专属的样式API,语法和原生CSS一致,还能自动适配MUI的主题配置。

方案3:MUI Grid布局(适合复杂场景)

如果需要和其他布局元素配合,可用Grid组件实现居中:

import { Button, Grid } from '@mui/material';

function App() {
  return (
    <Grid 
      container 
      justifyContent="center" 
      alignItems="center" 
      style={{ minHeight: '100vh' }}
    >
      <Grid item>
        <Button variant="contained">Hello World</Button>
      </Grid>
    </Grid>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:19