如何实现两个Material UI Grid容器的并排布局?
解决Material UI Grid并排显示问题
你的核心问题是用了两个独立的<Grid container>,这类容器默认是块级元素,会垂直堆叠,所以图片容器才会出现在列表下方。要实现并排,只需把图片和列表放到同一个父Grid容器里作为子项即可。
修改后的代码
return ( <> <Appbar /> <br /> {/* 顶级Grid容器,包裹两个并排的子项 */} <Grid container spacing={2} style={{marginTop:"50px"}}> {/* 左侧图片容器 - 占4列 */} <Grid item xs={4} display="flex" flexDirection="column" alignItems="center"> <img src={AllePakketjes} width="410" height="350" alt="Alle pakketjes" /> <h1 style={{ textAlign: "center", color: "white" }}>Alle pakketjes</h1> </Grid> {/* 右侧列表容器 - 占8列 */} <Grid item xs={8}> <Paper elevation={3} style={paperStyle}> {currentPosts.map(pakketje => ( <Paper elevation={6} style={{ margin: "10px", padding: "15px", textAlign: "left", backgroundColor: "white", borderRadius: "25px" }} key={pakketje.id}> <p style={{fontSize:"18px"}}><b>Pakketje </b></p> <b>ID: {pakketje.id}</b> <b>Status: {pakketje.status}</b> <b>Code: {pakketje.code}</b> <br /><br /> <Button variant="contained" style={{ backgroundColor: "#AE0000" }} color="secondary" onClick={(e) => deletePakketje(pakketje.id, e)}> Delete <DeleteIcon fontSize="small" /> </Button> <Link to={`/pakketjeUpdaten/${pakketje.id}`}> <Button variant="contained" style={{ backgroundColor: "Navy" }} color="secondary"> Update <ReplayIcon fontSize="small" /> </Button> </Link> <Button variant="contained" style={{ backgroundColor: "black" }} color="secondary" onClick={(e) => statusOnderweg(pakketje.id, e)}> Verzenden <LocalShippingIcon fontSize="small" /> </Button> <br /> <br /> </Paper> ))} </Paper> </Grid> </Grid> </> );
关键改动说明
- 新增顶级Grid容器:用
<Grid container>包裹两个子项,spacing属性用来控制子项之间的间距,避免手动加margin。 - 简化嵌套结构:原来的图片和列表里没必要再套
<Grid container>,直接用<Grid item>标记即可,减少不必要的层级。 - 调整列宽分配:
xs={4}和xs={8}是按12列网格系统分配宽度,你可以根据需求改成xs={6}+xs={6}等比例。 - 移除手动定位:删掉图片的
marginLeft: "365px",Grid会自动帮你完成水平排版,手动加定位会破坏Grid的布局逻辑。 - 优化图片容器排版:给图片的Grid item加了
display="flex"和alignItems="center",让图片和标题居中对齐,更美观。
内容的提问来源于stack exchange,提问作者Cezar P
相关产品推荐
相关产品推荐

