'React: how to get Material UI's grid spacing to work?
I am using Material UI's Grid (https://material-ui.com/api/grid) for my layout, however while the columns and rows are working fine, the spacing attribute doesn't seem to work.
I have imported Grid as such: import Grid from '@material-ui/core/Grid'
<Grid container spacing={10}>
<Grid item xs={12} sm={6}>
CONTENT
</Grid>
<Grid item xs={12} sm={6}>
CONTENT
</Grid>
</Grid>
But no padding appears.
Would anyone know how to I can include spacing in the grid?
Solution 1:[1]
For me problem was I was not using item for Grid items.
<Grid container spacing={3}>
<Grid item xs={12}></Grid>
<Grid item xs={12}></Grid>
</Grid>
Solution 2:[2]
Just having Content inside the <Grid> wouldn't work, but if you put it in a <div> or a <Paper> you would get what you need...
relevant js:
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
grid: {
textAlign: "center",
color: theme.palette.text.secondary
},
span: {
border: "1px solid pink",
backgroundColor: "lightpink`"
},
span2: {
border: "1px solid green",
backgroundColor: "lightgreen"
},
span3: {
border: "1px solid blue",
backgroundColor: "lightblue"
},
}));
const App = () => {
var classes = useStyles();
return (
<div className={classes.root}>
<Hello name="React" />
<p>Start editing to see some magic happen :)</p>
<br />
<Grid container spacing={10}>
<Grid item xs className={classes.grid}>
<div className={classes.span}>CONTENT</div>
</Grid>
<Grid item xs className={classes.grid}>
<div className={classes.span}>CONTENT</div>
</Grid>
</Grid>
<hr />
<Grid container spacing={8}>
<Grid item xs className={classes.grid}>
<div className={classes.span2}>CONTENT</div>
</Grid>
<Grid item xs className={classes.grid}>
<div className={classes.span2}>CONTENT</div>
</Grid>
</Grid>
<hr />
<Grid container spacing={6}>
<Grid item xs className={classes.grid}>
<div className={classes.span3}>CONTENT</div>
</Grid>
<Grid item xs className={classes.grid}>
<div className={classes.span3}>CONTENT</div>
</Grid>
</Grid>
</div>
);
};
example stackblitz here
Solution 3:[3]
I ran into this issue when using the sx prop on the Grid components. Be sure to place any custom styling only on children of the Grid components.
Solution 4:[4]
Grid spacing is applied as padding, when your using the xs or sm, there padding will overide the top one, so you will get the top bottom padding
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamza Khursheed |
| Solution 2 | Akber Iqbal |
| Solution 3 | Peter Nordman |
| Solution 4 | Raj Kumar |

