Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a component in MUI and make it responsive?

I don't quite understand the React Material-UI grid system. If I want to use a form component for login, what is the easiest way to center it on the screen on all devices (mobile and desktop)?

like image 897
zorro Avatar asked Jun 08 '18 18:06

zorro


People also ask

How do I center content in MUI?

The direction=“column” actually adds horizontal centering implicitly. Since direction=”row”, we have to manually set the center alignment both vertically and horizontally. On the “Bottom Center” item, alignItems=“flex-end” adds the vertical bottom alignment and justify=“center” adds the horizontal centering.

How do you center a component in material UI?

To align a component to the center or right with React Material UI, we can add a flex container with the Grid component. We add the Grid component and add the container prop to make it a flexbox container. Then we set the justify prop to flex-end to align the child components on the right side.

How do you center a component 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.

How do you center a material UI button?

To center a button in React Material UI, we can put the button in a Grid component. And we set the justify prop of the Grid to 'center' and we set the container prop to true . to add the Grid prop with the container and justify props. We set justify to 'center' to center the items inside.


2 Answers

Since you are going to use this on a login page. Here is a code I used in a Login page using Material-UI

MUI v5

<Grid   container   spacing={0}   direction="column"   alignItems="center"   justifyContent="center"   style={{ minHeight: '100vh' }} >    <Grid item xs={3}>    <LoginForm />   </Grid>        </Grid>  

MUI v4 and below

<Grid   container   spacing={0}   direction="column"   alignItems="center"   justify="center"   style={{ minHeight: '100vh' }} >    <Grid item xs={3}>     <LoginForm />   </Grid>     </Grid>  

this will make this login form at the center of the screen.

But still, IE doesn't support the Material-UI Grid and you will see some misplaced content in IE.

As pointed by @max, another option is,

<Grid container justifyContent="center">   <Your centered component/> </Grid> 

Please note that versions MUIv4 and below should use justify="center" instead.

However, using a Grid container without a Grid item is an undocumented behavior.

Hope this will help you.

like image 197
Nadun Avatar answered Oct 25 '22 15:10

Nadun


Another option is:

<Grid container justify = "center">   <Your centered component/> </Grid> 
like image 43
Max Avatar answered Oct 25 '22 14:10

Max