3

I have a login page, with 2 textfields: username and password and login button, with the username field at the topmost, password field below it and the login button at the bottom. I want them to be at the center of the page always both vertically and horizontally. I tried this:

<Grid
    className={classes.container}
    container
    spacing={16}
    direction="column"
    justify="center"
    alignItems="center"
>
    <Grid item xs={12}>
        <TextField />
    </Grid>
    <Grid item xs={12}>
        <TextField />
    </Grid>
    <Grid item xs={12}>
        <Button />
    </Grid>
</Grid>

It only centers horizontally. How can I make it center both horizontally and vertically?

Karias Bolster
  • 955
  • 3
  • 17
  • 31
  • Centering elements vertically with material-ui is not different from centering elements vertically with classical CSS. The simplest solution these days is to use the flexbox css model like this : https://stackoverflow.com/questions/19026884/flexbox-center-horizontally-and-vertically – Ricovitch Aug 13 '18 at 15:39

1 Answers1

3

you have almost got the answer, problem with your solution is you haven't provided the height for your page so the correct answer will be:

const styles = theme => ({
  content: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.default,
    padding: theme.spacing.unit * 3
  },
  container: {
    minHeight: "100vh"
  }
});

class LoginPage extends Component {
  render() {
    const { classes } = this.props;

    return (
      <div className={classes.content}>
        <Grid
          container
          spacing={16}
          direction="column"
          alignItems="center"
          justify="center"
          className={classes.container}
        >
          <Grid item xs={12}>
            text field
          </Grid>
          <Grid item xs={12}>
            text field
          </Grid>
          <Grid item xs={12}>
            <Button variant="raised" color="primary">
              Login
            </Button>
          </Grid>
        </Grid>
      </div>
    );
  }
}

please find that minHeight is providing 100vh for the Grid container. here is an working example : https://codesandbox.io/s/zl90ywy4r3

hope this will help you.

Nadun
  • 7,463
  • 1
  • 21
  • 27