如何在Material-UI中居中一个按钮

33

我不知道怎么在Material-UI中将按钮居中。这是我的代码:

function BigCard(props) {
    const { classes } = props;
    return (
    <div>
        <Card className={classes.card}>
        <CardContent>
            <Typography variant="display1" className={classes.title}>
            Start Funding!
            </Typography>
        </CardContent>
        <CardActions >
            <Button size="small" color="primary" className={classes.actions}>
            Share
            </Button>
            <Button size="small" color="primary">
            Learn More
            </Button>
        </CardActions>
      </Card>
    </div>
  );

我该如何将我的按钮居中显示?


1
添加代码时请使用文本而非图像。另外,请尽量提供最小可验证示例: https://stackoverflow.com/help/mcve - MUlferts
13个回答

51

您可以使用 Box 元素。

<Box textAlign='center'>
  <Button variant='contained'>
     My button
  </Button>
</Box>

32

你可以使用 Material UI 文档中的 覆盖样式类(override with classes)

第一种方法

你可以像这样做:

//Add your justify css in your styles const
const styles = {
    ...
    root: {
        justifyContent: 'center'
    }
};

使用“classes”属性将此添加到您的CardActions组件中:

 <CardActions classes={{root: classes.root}}>

第二种方法(更简单)

或者你可以直接在你的组件上使用样式,但是如果你经常使用material-ui,我建议你练习如何使用类。

只需像这样做:

<CardActions style={{justifyContent: 'center'}}>

18

对于避免定义 CSS 的使用情况

<Grid container justify="center">
  {props.children}
</Grid>

7

以下是我如何使用Material-UI实现的

import {Typography, Button} from '@material-ui/core';

 <Typography align='center'>
    <Button
      color='primary'
      size='large'
      type='submit'
      variant='contained'
     >
      Sign Up
    </Button>
  </Typography>

7
MUI v5 开始,您可以使用 sx 属性应用自定义样式。由于 CardActions 布局已经是弹性布局,所以您只需要将其 justify-content 设置为 center

使用 sx 而不是像其他答案中的内联样式有助于减少 CSS 特殊性,并使未来更容易覆盖 CSS。
<CardActions sx={{ justifyContent: "center" }}>
  <Button size="small">Learn More</Button>
</CardActions>

演示

编辑 51010599/material-ui中如何居中按钮


7

快速粗略:

<Button style={{margin: '0 auto', display: "flex"}}>
  NEXT
</Button>

4
我尝试的方法如下,也在YouTube上的Material UI官方视频中展示。
<Grid item xs={12} sm={12} md={4} lg={4}
    style={{
        textAlign:'center' // this does the magic
    }}
>
    <Button>
         NEXT
    </Button>
</Grid>

谢谢并致以最好的祝愿。

尝试了以上所有方法,但都没有用,只有这个有效! - ogg130

2

您需要使用两个属性:display和justify-content。

<CardActions display='flex' justifyContent='center'>

我正在使用Grid Material UI进行工作。添加了<Grid display="flex" justifyContent="center">,只有在这两个属性都定义的情况下才能正常工作。 - joekevinrayan96

0

这可能听起来有些违反直觉,但对于我的情况(与你的略有不同),使用 Button 元素中的 fullWidth 属性是有效的。

以下是我的场景(MUI v5):

<Grid container alignItems={'center'} >
  <Grid item>
    <Button fullWidth variant='contained' >Click Me!</Button>
  </Grid>
</Grid>

0

将元素包裹在这个中心

.center{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

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