You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Material-UI React应用中Grid子项水平居中及间距问题求助

Solution to Center Material-UI Grid Items Horizontally with Spacing

Hey there! Let's fix your Grid layout issues. The main problems are missing horizontal centering and ensuring the spacing between items works as expected. Here's how to resolve it:

Key Changes Needed

  • Horizontal Centering: Replace alignContent="center" and alignItems="center" with justifyContent="center" on your Grid container. The justifyContent property controls alignment along the main axis (horizontal, since the default direction is row), while alignItems/alignContent handle vertical alignment.
  • Spacing: Your spacing={3} prop is already correct! Material-UI adds padding to each Grid item and negative margins to the container to create consistent spacing between items—it just wasn't obvious when your items were left-aligned.

Modified Code

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Container, Grid } from "@material-ui/core";
import TextField from "@material-ui/core/TextField";

const useStyles = makeStyles((theme) => ({
  topContainer: {
    marginTop: theme.spacing(5),
  },
}));

export const AddContact = () => {
  const classes = useStyles();
  return (
    <Container fixed>
      <Grid 
        container 
        spacing={3} 
        justifyContent="center"  // This centers items horizontally
        className={classes.topContainer} 
      >
        <Grid item xs={4} style={{ border: "1px solid #ccc" }}>
          <TextField id="name" label="Name" style={{ width: "100%" }} />
          <TextField id="userName" label="User Name" style={{ width: "100%" }} />
        </Grid>
        <Grid item xs={4} style={{ border: "1px solid #ccc" }}>
          STEP 2
        </Grid>
      </Grid>
    </Container>
  );
};

Explanation

  • justifyContent="center" pushes your two xs={4} Grid items to the center of the container, with the remaining 4 columns (12 total - 4 -4) split equally on either side.
  • The spacing={3} ensures there's a 24px gap (since theme.spacing(1) = 8px) between the two items. Adjust the number to make the spacing larger or smaller (e.g., spacing={2} for a 16px gap).

If you also want to center items vertically within the container, you can add alignItems="center" back in—just make sure the container has a defined height (otherwise it won't have any visible effect).

内容的提问来源于stack exchange,提问作者Ashy Ashcsi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:14:41