How to align a component to the center/right

2020-08-09 05:51发布

问题:

I want to align my button to the right of the parent.

I was wondering if there is a proper way to do it in material-ui. I could use a <Grid container justify="flex-end"> but then I would have to use another <Grid item />. Seems too much of work.

Or maybe I am just better off using plain old CSS, messing around with float: right and dealing with the apparent zero height of the element.

回答1:

Try this

<Grid container alignItems="flex-start" justify="flex-end" direction="row">
     <Button variant="contained">Add account</Button>
</Grid>


回答2:

If you do not want to use the Grid component, you have to rely on CSS.

But if you use Material-UI you should use JSS (CSS-IN-JS) and not plain CSS.

  • Introduction : https://material-ui.com/customization/css-in-js/
  • Benefits : http://cssinjs.org/benefits

In CSS you may use any of these solutions for example. "text-align" being the simplest one.

  • text-align: right
  • float: right
  • flexbox
    • parent with : display: flex
    • child with : align-content: flex-end


回答3:

Material UI's Grid Component has helper props to achieve this.

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

You can find the docs here.