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

使用Material UI无法将元素置于屏幕正中央,请求排查问题

解决Material UI元素无法垂直居中到屏幕中央的问题

你的代码只实现了水平居中,没能垂直居中到屏幕中央,问题出在两个地方:

  • 外层div设置了width: 100%; height:100%,但它的父级(html、body)默认没有占满视口高度,导致这个div的高度并没有覆盖整个屏幕。
  • 负责布局的Box组件仅配置了justifyContent: 'center'(控制水平居中),缺少垂直居中的相关设置,且自身没有占满父容器高度。

修复方案

我们可以直接通过调整外层容器和Box的样式来解决:

  1. 给外层容器添加minHeight: '100vh'(确保占满整个视口高度),同时把它设为flex容器,用alignItems: 'center'实现垂直居中。
  2. 移除Box上不必要的textAlign,让flex布局来控制居中。

修改后的完整代码:

import * as React from 'react';
import Box, { BoxProps } from '@mui/material/Box';

function Item(props: BoxProps) {
  const { sx, ...other } = props;
  return (
    <Box
      sx={{
        p: 1,
        m: 1,
        bgcolor: (theme) => (theme.palette.mode === 'dark' ? '#101010' : 'grey.100'),
        color: (theme) => (theme.palette.mode === 'dark' ? 'grey.300' : 'grey.800'),
        border: '1px solid',
        borderColor: (theme) =>
          theme.palette.mode === 'dark' ? 'grey.800' : 'grey.300',
        borderRadius: 2,
        fontSize: '0.875rem',
        fontWeight: '700',
        ...sx,
      }}
      {...other}
    />
  );
}

export default function JustifyContent() {
  return (
    <div style={{ width: '100%', minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <Box
        sx={{
          p: 1,
          m: 1,
          bgcolor: 'background.paper',
          borderRadius: 1,
        }}
      >
        <Item>Item 1</Item>
      </Box>
    </div>
  );
}

或者也可以用Material UI的Box代替外层div,写法更统一:

import * as React from 'react';
import Box, { BoxProps } from '@mui/material/Box';

function Item(props: BoxProps) {
  const { sx, ...other } = props;
  return (
    <Box
      sx={{
        p: 1,
        m: 1,
        bgcolor: (theme) => (theme.palette.mode === 'dark' ? '#101010' : 'grey.100'),
        color: (theme) => (theme.palette.mode === 'dark' ? 'grey.300' : 'grey.800'),
        border: '1px solid',
        borderColor: (theme) =>
          theme.palette.mode === 'dark' ? 'grey.800' : 'grey.300',
        borderRadius: 2,
        fontSize: '0.875rem',
        fontWeight: '700',
        ...sx,
      }}
      {...other}
    />
  );
}

export default function JustifyContent() {
  return (
    <Box sx={{ width: '100%', minHeight: '100vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
      <Box
        sx={{
          p: 1,
          m: 1,
          bgcolor: 'background.paper',
          borderRadius: 1,
        }}
      >
        <Item>Item 1</Item>
      </Box>
    </Box>
  );
}

内容的提问来源于stack exchange,提问作者S.Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:24:19