使用Material UI无法将元素置于屏幕正中央,请求排查问题
解决Material UI元素无法垂直居中到屏幕中央的问题
你的代码只实现了水平居中,没能垂直居中到屏幕中央,问题出在两个地方:
- 外层div设置了
width: 100%; height:100%,但它的父级(html、body)默认没有占满视口高度,导致这个div的高度并没有覆盖整个屏幕。 - 负责布局的Box组件仅配置了
justifyContent: 'center'(控制水平居中),缺少垂直居中的相关设置,且自身没有占满父容器高度。
修复方案
我们可以直接通过调整外层容器和Box的样式来解决:
- 给外层容器添加
minHeight: '100vh'(确保占满整个视口高度),同时把它设为flex容器,用alignItems: 'center'实现垂直居中。 - 移除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
相关产品推荐
相关产品推荐

