如何让Material UI Grid子项随视口缩放且保持正方形比例?
实现Material UI Grid子项的正方形自适应缩放
方法1:使用CSS aspect-ratio 属性(推荐)
现代浏览器原生支持aspect-ratio属性,直接设置宽高比为1:1就能让高度自动匹配宽度,完美实现正方形自适应。只需把原代码中固定的height替换成aspectRatio: 1即可:
<Box sx={{ width: { xs: "calc(100% - 4px)", lg: "calc(100% - 4px)", xl: "100%" }, // 替换固定height,设置1:1宽高比 aspectRatio: 1, border: "1px solid black", borderRadius: 2, display: "flex", justifyContent: "center", alignItems: "center", cursor: "pointer" }} > test </Box>
方法2:padding-bottom技巧(兼容旧浏览器)
如果需要兼容不支持aspect-ratio的旧浏览器,可以利用padding百分比基于父元素宽度计算的特性,通过外层容器撑开高度:
<Grid item key={tile} xs={1} lg={1} xl={1}> {/* 外层容器:用padding-bottom实现正方形比例 */} <Box sx={{ width: { xs: "calc(100% - 4px)", lg: "calc(100% - 4px)", xl: "100%" }, position: "relative", paddingBottom: "100%" // 高度等于自身宽度 }} > {/* 内部内容Box:绝对定位填满容器 */} <Box sx={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, border: "1px solid black", borderRadius: 2, display: "flex", justifyContent: "center", alignItems: "center", cursor: "pointer" }} > test </Box> </Box> </Grid>
额外优化:简化宽度计算
原代码中手动计算calc(100% -4px)其实可以省略——Grid组件的columnSpacing和rowSpacing已经会自动处理子项间距,直接把宽度设为100%即可,更符合Material UI的设计逻辑:
<Grid container columns={{ xs: 2, lg: 2, xl: 4 }} rowSpacing={{ xs: 1, xl: 2 }} columnSpacing={{ xs: 1, xl: 2 }} > {tiles.map((tile) => ( <Grid item key={tile} xs={1} lg={1} xl={1}> <Box sx={{ width: "100%", aspectRatio: 1, border: "1px solid black", borderRadius: 2, display: "flex", justifyContent: "center", alignItems: "center", cursor: "pointer" }} > test </Box> </Grid> ))} </Grid>
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

