Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center component inside the material-ui grid

I want to use same cards and make them center aligned, I searched and tried some solutions but all of them align only the component grid, and not the component content itself (I need them to be equally distant form the borders and from themselves).

enter image description here enter image description here

I'm using this code (https://codesandbox.io/embed/32o8j4wy2q):

<Grid
      container
      spacing={0}
      direction="column"
      alignItems="center"
      justify="center"
      style={{ minHeight: '80vh' }}>
      <Grid container item xs={12} spacing={8}>
        <Grid item xs={6}>
          <Card />
        </Grid>
        <Grid item xs={6}>
          <Card />
        </Grid>
        <Grid item xs={6}>
          <Card />
        </Grid>
        <Grid item xs={6}>
          <Card />
        </Grid>
      </Grid>
    </Grid>

The card code is irrelevant but I just copied the material-ui's example one.

Also, how do I use flexboxes (or other tool) to auto align if I decide in the future to add or remove some cards?

like image 823
Pedro Vieira Avatar asked Mar 26 '19 18:03

Pedro Vieira


People also ask

How do you center items in Mui grid?

The “Center L.” item uses the alignItems: “center” style to control the vertical alignment of the Grid contents. The contents are left aligned by default but you could have chosen to include justifyContent: “flex-start” . The “Bottom L” item I use a mix of inline style and MUI Grid API just to show it is possible.

How do I set my grid to center?

To center the <div> element horizontally using grid. Use the property of display set to grid i.e. display: grid; Then use property place-items: center; Example: The following example demonstrates to set the <div> to the center using grid property.

How do you center a component of a react?

To center a component horizontally and vertically in React. js, set its display property to flex and its alignItems and justifyContent properties to center . The components's content will be horizontally and vertically centered.


Video Answer


1 Answers

I soved it by adding align="center" in the JSX code that means align-items: center in CSS as explained here.

The code was done like this:

  <Fragment>
    <Grid
      container
      spacing={24}
      justify="center"
      style={{ minHeight: '100vh', maxWidth: '100%' }}
      >
     <Grid item xs={3} align="center">
        <Card />
      </Grid>
      <Grid item xs={3} align="center">
        <Card />
      </Grid>
      <Grid item xs={3} align="center">
        <Card />
      </Grid>
      <Grid item xs={3} align="center">
        <Card />
      </Grid>
    </Grid>
  </Fragment>
like image 192
Pedro Vieira Avatar answered Sep 27 '22 19:09

Pedro Vieira