How to center a grid in MaterialUI

Viewed 200

I am trying to create 3 paper elements in the vertical and horizontal center of the screen. No matter what css rules I apply or props, when I inspect the HTML elements in the console, the height of HTML is always 76 pixels, and the elements wont go any lower than the height of that div. I'm really at a loss here.

import React from 'react';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles({
  grid: {
    height: "100%"
  },
      paper: {
      height: 140,
      width: 100,
    },
});

export default function SpacingGrid() {
  const classes = useStyles();

  return (
      <Grid
        className={classes.grid}
        container
        justify="center"
        alignItems="center"
        spacing={2}
      >
        {[0, 1, 2].map((value) => (
            <Grid key={value} item>
              <Paper className={classes.paper} />
            </Grid>
          ))}
      </Grid>
  );
}
import React from 'react';
import ReactDOM from 'react-dom';
import SpacingGrid from './SpacingGrid';

ReactDOM.render(
  <React.StrictMode>
    <SpacingGrid />
  </React.StrictMode>,
  document.getElementById('root')
);
2 Answers
const useStyles = makeStyles({
  grid: {
    position: "absolute", // add this.
    height: "100%"
  },
      paper: {
      height: 140,
      width: 100,
    },
});

here is the sandbox link.

To center both horizontally and vertically to the viewport, one needs to make the <html>, <body>, and <div id="root"> fill the viewport. To do this, create a file style.css:

html,
body,
#root {
  height: 100vh;
}

and then import the styles anywhere in your React project. For example, import it in index.js:

import React from "react";
import ReactDOM from "react-dom";
import SpacingGrid from './SpacingGrid';
import "./style.css";  // Add this!

ReactDOM.render(
  <React.StrictMode>
    <SpacingGrid />
  </React.StrictMode>,
  document.getElementById("root")
);

Here is a live version on stackblitz

Related