如何使用Material UI将组件居中/靠右对齐?

87
我想将我的按钮与其父元素右对齐。
我想知道在Material UI中有没有适当的方法可以实现它。我可以使用以下代码:
<Grid container justify="flex-end">

但这样我就得使用另一个 <Grid item />,看起来太麻烦了。

或者也许我最好还是使用普通的 CSS,尝试使用 float:right,并处理元素明显的零高度。

9个回答

131

Material UI 5之前:

试试这个

<Grid container justify="flex-end">
  <Button>Example</Button>
</Grid>

更新 Material UI 5:(感谢 Dipak)

ForwardRef(Grid) 的属性 justify 已被弃用。请改用 justifyContent,该属性已更名。

<Grid container justifyContent="flex-end">
  <Button>Example</Button>
</Grid>

更新:最佳解决方案是NearHuscarl或Eduardo Oviedo Blanco的答案,您最好使用Stack或Box而不是Grid。


3
如果容器 Grid 中有两个 Grid 项,而我只想将第二个项向右对齐,应该怎么做? - Imran Ahmad
12
然后,您将把您的项目转换为一个容器(一个网格可以是两者兼备),因此您的项目将类似于:<Grid item xs={6} container justify="flex-end">。 - ThomasP1988
5
<Grid item xs={12} sm={6} container justifyContent="flex-end">的添加对我有用。必须使用justifyContent - Prakhar

47

如果您想在<Grid item>中对齐项目,您可以使用以下包装Box组件:

<Grid container>
  <Grid item sm={6}>
    <Box display="flex" justifyContent="flex-end">
      <Button>Button Aligned To The Right</Button>
    </Box>
  </Grid>
</Grid>

请参阅文档以获取更多定位选项。


14
Material UI v5中,您可以使用Stack将一组组件显示在行或列上。Stack是一个flexbox,所以您只需要设置justifyContent属性来对齐其中的项目:
<Stack direction="row" justifyContent="end">
  <Button variant="contained">Item 1</Button>
</Stack>

Codesandbox Demo


3

如果您不想使用Grid组件,则必须依赖CSS。

但是,如果您使用Material-UI,应该使用JSS(CSS-IN-JS)而不是普通的CSS。

在CSS中,您可以使用以下任何解决方案,例如“text-align”是最简单的一种。

  • text-align: right
  • float: right
  • flexbox
    • 父元素使用:display: flex
    • 子元素使用:align-content: flex-end

2
            <Toolbar sx={{ display: "flex", justifyContent: "space-between" }}>
                <Typography sx={{ fontWeight: 600 }}>
                    Recent Repositories
                </Typography>
                <Box>
                    {/* <Typography></Typography> */}
                    <Button error>+ New</Button>
                </Box>
            </Toolbar>

2

使用具有弹性的Box组件。

<Box display="flex" flexDirection="column" >
  <... other stuff/>
</Box>

您可以在此处了解更多相关的IT技术内容。


1

对于最新的material-ui 5版本,请使用justifyContent="flex-end"或alignContent,它相当于css text-align和flex-end=right。

    <Grid container alignContent="flex-end">
         <Button>Example</Button>
    </Grid>

or
    <Grid item justifyContent="flex-end">
         <Button>Example</Button>
    </Grid>

对于旧的 material-ui 版本 4

    <Grid item justify="flex-end">
         <Button>Example</Button>
    </Grid>

只有在 v4.11.4<Grid container justify="flex-end"> 才有效。你的例子对我不起作用。 - aemaem
谢谢,这对我很有帮助,节省了我的时间。 - sms247
你能否指定版本,而不是使用“最新”[在撰写本文时]和“旧”的说法? - nafg

0

由于这个问题并没有特别针对Grid,所以这里提供一个更一般性的答案:

还有其他组件需要在sx中提供参数。

<Toolbar sx={{ justifyContent: 'flex-end' }}>

-3

Material UI的Grid组件有辅助属性可以实现这一点。

<Grid align-items-xs-center justify-xs-flex-end>
 <Button>Click me</Button>
</Grid>

你可以在这里找到文档。


3
可能是在旧版中,且没有回答问题。 - Hugo Gresse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接