I have a basic Grid
using a spacing of 5
. I want that spacing not to happen at the xs
breakpoint. How can I remove it on the xs
breakpoint?
You can see a demo here.
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
}));
export default function SpacingGrid() {
const classes = useStyles();
return (
<Grid container justify="center" spacing={5}>
<Grid item>
<Paper className={classes.paper} />
</Grid>
<Grid item>
<Paper className={classes.paper} />
</Grid>
<Grid item>
<Paper className={classes.paper} />
</Grid>
</Grid>
);
}
Here are two steps to completely remove padding from the MUI Grid: Completely remove the spacing prop (or set spacing={0}) Make sure no padding is applied in the sx prop or classes.
The spacing property is an integer between 0 and 10 inclusive. By default, the spacing between two grid items follows a linear function: output(spacing) = spacing * 8px, e.g. spacing={2} creates a 16px wide gap.
Basic grid For example, xs={12} sizes a component to occupy the whole viewport width regardless of its size.
I think the useMediaQuery hook in combination with theme breakpoints is just what you need.
import { useTheme } from '@material-ui/core/styles';
import useMediaQuery from '@material-ui/core/useMediaQuery';
function MyComponent() {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down('sm'));
return <Grid spacing={isSmall ? 0 : 2}> ... ;
}
See useMediaQuery - css media query hook.
Grid
's spacing prop can accept both a number and an object that describes what value should be set on different breakpoints:
A simple number applied to all breakpoints:
<Grid container spacing={3}
A responsive values based on breakpoints, more detail on here:
<Grid
container
spacing={{
xs: 0,
sm: 2,
md: 5
}}
>
I was able to get it to work using this CSS hackery, but I was hoping for a solution only using props though.
const pageStyles = theme => ({
leftColumn: {
[theme.breakpoints.down('sm')]: {
margin: 0,
'& > .MuiGrid-item': {
padding: 0,
},
},
}
});
<Grid
item
container
spacing={5}
classes={{
root: classes.leftColumn,
}}
>
...
</Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With