DEV Community

Haruka Kato
Haruka Kato

Posted on

How to place Grid in center in React

I was trying to center element to center but

margin: 0 auto
display: block
Enter fullscreen mode Exit fullscreen mode

nor

margin: 10px auto;
Enter fullscreen mode Exit fullscreen mode

worked.
I researched and those solutions don't work for because it a block-level element by default, and which therefore occupies 100% width as you can see from the picture.
Screen Shot 2021-02-11 at 10.39.43

Here is the code I was trying to apply.

    return (
        <React.Fragment>
            <Header/>
            <Box
                className={classes.box}
                style={{
                    color: "#white"
                }}>
                <h2 className={classes.font}>Your customized stress release plan.</h2>
                <p className={classes.font}>20% complete</p>
                <h1 className={classes.font} >How did your stress change over the month?</h1>
                <h3 className={classes.font}>Select all that apply(required)</h3>
                    <Grid container className={classes.grid} >
                        <Grid item xs={6} sm={2} >
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                        <Grid item xs={6} sm={2}>
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                        <Grid item xs={6} sm={2}>
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                    </Grid>
                    <Grid container >
                        <Grid item xs={6} sm={2}>
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                        <Grid item xs={6} sm={2}>
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                        <Grid item xs={6} sm={2}>
                            <Paper className={classes.paper}>xs=6 sm=3</Paper>
                        </Grid>
                    </Grid>
                <Button variant="contained" color="primary" disableElevation className={classes.button}>
                    <Link to="/question2">⇨ Go to questions</Link>
                </Button>
            </Box>
            <Footer/>
        </React.Fragment>
    );
Enter fullscreen mode Exit fullscreen mode

You could use

    margin: '0 auto',
    width: '50%',
Enter fullscreen mode Exit fullscreen mode

but in my case, it already specifies the width so applying this makes the grid smaller.

So I used this.

    grid:{
        justifyContent: 'center',
        alignContent:  'center',
    },
Enter fullscreen mode Exit fullscreen mode

I hope this helps those who are trying to center Grid element.

Top comments (0)