简体   繁体   中英

Problem with using Material UI <Grid> for two column layout

I'm trying to achieve a two column layout, both of them equal height and each taking half of the screen. Picture explains it better, here is one .

The not working code is as follows:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    alignItems: "stretch"
  },
  column: {
    flexDirection: "column"
  },
  paper: {
    padding: theme.spacing(2),
    textAlign: "center",
    color: theme.palette.text.secondary
  }
}));

export default props => {
  const classes = useStyles();
  return (
    <>
      <CssBaseline />
      <Grid container className={classes.root}>
        {/* COLUMN ONE */}
        <Grid container item className={classes.column}>
          <Grid item xs={6}>
            <Paper className={classes.paper}>1: xs=6</Paper>
          </Grid>
          <Grid item xs={6}>
            <Paper className={classes.paper}>1: xs=6</Paper>
          </Grid>
          <Grid container item>
            <Grid item xs={3}>
              <Paper className={classes.paper}>1: xs=3 left</Paper>
            </Grid>
            <Grid item xs={3}>
              <Paper className={classes.paper}>1: xs=3 right</Paper>
            </Grid>
          </Grid>
        </Grid>
        {/* COLUMN TWO */}
        <Grid container item className={classes.column}>
          <Grid item xs={6}>
            <Paper className={classes.paper}>2: xs=6</Paper>
          </Grid>
          <Grid item xs={6}>
            <Paper className={classes.paper}>2: xs=6</Paper>
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};

Obligatory codesandbox is here .

Could someone explain me what am I doing wrong here?

There's a bug with Material UI way of laying out nested grid containers, here . The workaround - found by @londonoliver - is to nest containers inside the grid items:

<Grid container direction="row">
  <Grid item>
    <Grid container direction="column">
      <Grid item>1</Grid>
      <Grid item>2</Grid>
    </Grid>
  </Grid>
  <Grid item>
    <Grid container direction="column">
      <Grid item>3</Grid>
      <Grid item>4</Grid>
    </Grid>
  </Grid>
</Grid>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM