React MUI响应式Grid布局优化:修复多屏显示异常问题
问题修复代码及说明
修改后的完整代码
import { Box, Grid, Paper, Typography } from "@mui/material"; import { styled } from "@mui/material/styles"; const Contained = styled(Box)({ backgroundColor: "rgba(241, 243, 246, 1)", fontFamily: "Roboto", minHeight: "100vh", width: "100vw", paddingTop: "24px", }); const Appbox = styled("div")({ backgroundColor: "#fff", border: "1px solid #E4E9F2", borderRadius: "4px", color: "#64768C", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", padding: "16px", textAlign: "center", height: "92px", width: "100%", "&:hover": { boxShadow: "0px 3px 6px #00000029", }, }); const StatsNumber = styled(Typography)({ fontSize: "32px", fontWeight: 600, }); function ResponsiveGrid() { const boxes = Array.from({ length: 9 }, (_, index) => index + 1); return ( <Contained> <Typography align="left" variant="h1" sx={{ margin: "0 32px 24px 32px", fontSize: "24px" }} > Dashboard </Typography> <Grid item xs={12} sx={{ padding: "0 32px" }}> <Paper sx={{ padding: "32px" }}> <Grid container spacing={2} justifyContent="center"> {boxes.map((num) => ( <Grid key={num} item xl={1} lg={2} md={2} xs={4} > <Appbox> <StatsNumber>33</StatsNumber> <Typography>Text Here</Typography> </Appbox> </Grid> ))} </Grid> </Paper> </Grid> </Contained> ); } export default ResponsiveGrid;
关键修改点
解决大屏间距重叠
- 移除
Appbox的固定宽度133px,改为width: 100%,让盒子自适应Grid容器宽度,避免溢出重叠。 - 修正外层Grid的无效属性
xl={18}(MUI Grid最大为12列),改为xs={12}占满全屏。 - 给内层Grid容器添加
justifyContent="center",让9个盒子在大屏上均匀分布。
- 移除
修复移动端布局
- 将Grid item的
xs值从12改为4(12列布局中,xs={4}实现每行3个盒子),达成移动端3x3网格的需求。
- 将Grid item的
匹配响应式需求
- xl大屏(≥1536px):
xl={1},9个盒子刚好占满一行。 - 平板设备(≥900px):
lg={2}/md={2},每行显示6个盒子,9个盒子自动分为两行。 - 移动端(<600px):
xs={4},每行3个盒子,9个盒子分为3行。
- xl大屏(≥1536px):
代码优化
- 用数组循环生成9个盒子,减少重复代码。
- 将
Contained的height: 100vh改为minHeight: 100vh,避免内容超出时被截断。
内容的提问来源于stack exchange,提问作者Angela Rubchinksy
相关产品推荐
相关产品推荐

