如何使用MUI的styled工具实现两个div并排显示?
如何用MUI的styled工具让两个Box并排显示?
你当前的代码问题在于Wrapper仅设置了display: grid,但未定义网格列规则,默认是单列布局,所以两个Box会自动换行。以下几种方法都可以通过MUI的styled工具实现并排效果:
方法1:使用Grid布局(推荐用于需要精确列宽控制的场景)
修改Wrapper的样式,指定网格列数量和宽度:
const Wrapper = styled(Box)({ display: "grid", gridTemplateColumns: "1fr 1fr", // 两列等宽,可替换为固定值如"200px auto" gap: 16, // 可选,设置两元素之间的间距 });
方法2:使用Flex布局(推荐用于简单行内并排场景)
Flex布局更适合这种基础的横向排列需求,代码更简洁:
const Wrapper = styled(Box)({ display: "flex", gap: 16, // 可选,设置元素间距 // 若需要空间不足时自动换行,可添加: // flexWrap: "wrap", });
完整示例代码(Flex版本):
import React from 'react'; import Box from "@mui/material/Box"; import { styled } from "@mui/material/styles"; import { Container } from "@mui/material"; const Wrapper = styled(Box)({ display: "flex", gap: 16, }); const App = (props) => { return ( <Container> <Wrapper> <Box>text here</Box> <Box>more text</Box> </Wrapper> </Container> ) } export default App
方法3:给Box设置inline-block(备选方案)
直接为每个Box设置inline-block属性,也能实现并排:
const StyledBox = styled(Box)({ display: "inline-block", marginRight: 16, // 手动设置间距 }); // 组件中使用 <Wrapper> <StyledBox>text here</StyledBox> <StyledBox>more text</StyledBox> </Wrapper>
上述方法均基于MUI的styled工具实现,无需额外依赖,完全适配你的场景。
内容的提问来源于stack exchange,提问作者Woodchuck
相关产品推荐
相关产品推荐

