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"andalignItems="center"withjustifyContent="center"on your Grid container. ThejustifyContentproperty controls alignment along the main axis (horizontal, since the default direction is row), whilealignItems/alignContenthandle 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 twoxs={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 (sincetheme.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
相关产品推荐
相关产品推荐

