【问题标题】:how to align a grid item center in material-ui in react?如何在反应中对齐material-ui中的网格项目中心?
【发布时间】:2021-11-30 07:55:01
【问题描述】:

我有一个 maxWidth 的网格元素,以便在大屏幕上显示时具有水平边距。我希望网格元素居中,并且长段落应与左侧对齐。你会怎么做?我正在使用 MUI v5。谢谢。

 <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>

【问题讨论】:

  • 您好@watanabe.N,只需在Box 样式中添加textAlign: 'center' 即可。

标签: css reactjs material-ui


【解决方案1】:

使用system properties 很简单。

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

【讨论】:

  • 很高兴有帮助!请检查您是否确信这是一个正确的答案。
【解决方案2】:

你可以试试下面的代码。我检查了这段代码,它运行良好。

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>
  );
}

【讨论】:

  • 谢谢,但这不起作用。
  • 我确认此代码here
  • 谢谢,但长文本未与左侧对齐:/
  • 类似于标题文本集 align="center" 道具,用于长文本排版。我也更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 2021-07-29
  • 2020-05-21
  • 2020-04-25
  • 2021-08-16
  • 1970-01-01
  • 2023-04-10
  • 2021-04-08
相关资源
最近更新 更多