首页 > 解决方案 > 如何在 Material-UI Grid 项目之间应用边距?

问题描述

我们如何在 Material-UI Grid 项目之间添加边距(空白区域)?

容器的间距属性仅在项目上添加填充。

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

const useStyles = makeStyles({
  root: {
    backgroundColor: "red"
  },
  root2: {
    backgroundColor: "green"
  }
});

function App() {
  const classes = useStyles();
  return (
    <Grid container spacing={2}>
      <Grid item xs={6} className={classes.root}>
        hi
      </Grid>
      <Grid item xs={6} className={classes.root2}>
        hi
      </Grid>
    </Grid>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

标签: reactjsmaterial-ui

解决方案


更改 xs 属性,使该行中的总数小于 12 以留出一些空间。

margin: "auto"根据需要为您的项目添加或任何其他边距。

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

const useStyles = makeStyles({
  root: {
    backgroundColor: "red",
    margin: "auto"
  },
  root2: {
    backgroundColor: "green",
    margin: "auto"
  }
});

function App() {
  const classes = useStyles();
  return (
    <Grid container spacing={2}>
      <Grid item xs={5} className={classes.root}>
        hi
      </Grid>
      <Grid item xs={5} className={classes.root2}>
        hi
      </Grid>
    </Grid>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

推荐阅读