You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何让Material-UI的Button与IconButton在同一行显示

解决Material-UI Grid中Button与IconButton同行显示的问题

嘿,刚上手Material-UI确实容易在Grid布局上摸不清门道,我来帮你快速搞定这个问题!

问题根源

你当前的代码里,两个Grid item都设置了xs={12}——这个属性表示在最小屏幕断点(xs,即宽度<600px)下,每个item会占据整行12份的宽度,所以它们自然会上下排列。而align="center"只是控制垂直方向的对齐,和换行没有关系哦。

解决方案

有几种简单的方式可以让两个按钮同行显示,同时保持你想要的居中效果:

方案1:将两个按钮放入同一个Grid Item(推荐)

把按钮都放到一个xs={12}的item里,利用Flex布局来排列它们,同时保持整体居中:

<Grid container spacing={1} align="center" justifyContent="center">
  <Grid item xs={12} display="flex" gap={1}>
    <Button variant="contained" color="secondary" onClick={this.leaveButtonPressed} >
      Leave Room
    </Button>
    <IconButton color="primary" onClick={() => this.updateShowSettings(true)}>
      <SettingsIcon />
    </IconButton>
  </Grid>
</Grid>
  • display="flex":让item内部的元素使用Flex布局,自动横向排列
  • gap={1}:控制两个按钮之间的间距(和外层Grid的spacing对应)
  • justifyContent="center":让整个container内的内容水平居中,保持你想要的页面居中效果

方案2:调整Grid Item的宽度

去掉每个item的xs={12},让它们自动收缩到内容宽度,同时通过container的justifyContent控制整体居中:

<Grid container spacing={1} align="center" justifyContent="center">
  <Grid item>
    <Button variant="contained" color="secondary" onClick={this.leaveButtonPressed} >
      Leave Room
    </Button>
  </Grid>
  <Grid item>
    <IconButton color="primary" onClick={() => this.updateShowSettings(true)}>
      <SettingsIcon />
    </IconButton>
  </Grid>
</Grid>

这里的spacing={1}会自动给两个item之间加上间距,效果也很整洁。

小提示

Material-UI的Grid组件是基于CSS Flexbox实现的,所以很多原生Flex的属性都可以通过props直接传递(比如display、flexDirection、justifyContent等),上手之后可以灵活运用这些属性来实现各种布局~

内容的提问来源于stack exchange,提问作者Vito Palmieri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:32:50