简体   繁体   中英

how to align a grid item center in material-ui in react?

I have a grid element with maxWidth so that it has horizontal margin when displayed in a big screen. I want the grid element to be centered and a long paragraph should be aligned to the left side. How would you do? I'm using MUI v5. Thank you.

 <Box
      style={{
        backgroundColor:"rgb(234, 237, 242)"
      }}      
    >
      <Grid container alignItems='center' justifyContent='center' maxWidth='md'>
        <Grid item xs={12} md={12} justifyContent="center">   
            <Typography align="center" variant="h4" style={{ fontWeight: 800 }} sx={{mb:4}}>
              Nice title
          </Typography>
            <Typography sx={{ px: 4 }} paragraph>very very long line. very very long line. very very long line. very very long line. very very long line. very very long line. very very long line. very very long line. very very long line. very very long line. very very long line.</Typography>
          </Grid>
        </Grid> 
    </Box>

在此处输入图像描述

It's simple enough using system properties .

    <Box
      display="flex"
      justifyContent="center"
      style={{
        backgroundColor:"rgb(234, 237, 242)"
      }}
    >
      ...

You can try the following code. I have checked this code it is working perfectly.

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';

const Item = styled(Paper)(({ theme }) => ({
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  color: theme.palette.text.secondary,
}));

export default function BasicGrid() {
  return (
    <Box sx={{ flexGrow: 1, backgroundColor: 'rgb(234, 237, 242)' }}>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <Item>
            <Typography align="center" variant="h4" style={{ fontWeight: 800 }} sx={{ mb: 4 }}>
              Hello
            </Typography>
            <Typography align="center" sx={{ px: 4 }} paragraph>
              very very long line
            </Typography>
          </Item>
        </Grid>
      </Grid>
    </Box>
  );
}

you can add text-align: center; to Box tag like this:

 <Box
   style={{
    backgroundColor:"rgb(234, 237, 242)";
    textAlign: "center";
   }}
 > 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM