Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - How to center a grid in MaterialUI

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')
);
question from:https://stackoverflow.com/questions/65863559/how-to-center-a-grid-in-materialui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...