【问题标题】:Vertical align using MUI Paper使用 MUI Paper 垂直对齐
【发布时间】:2023-03-16 16:33:01
【问题描述】:

我想垂直对齐 MUI Paper 组件中的一些文本。

代码是here

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
    height: 200,
    verticalAlign: 'middle'
  },
}));

function PaperSheet() {
  const classes = useStyles();

  return (
    <div>
      <Paper className={classes.root}>
        <Typography variant="h5" component="h3">
          This is a sheet of paper.
        </Typography>
        <Typography component="p">
          Paper can be used to build surface or other elements for your application.
        </Typography>
      </Paper>
    </div>
  );
}

export default PaperSheet;

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    vertical-align CSS 属性仅适用于 display: block 元素。

    您可以选择使用 flexbox 声明 root 类:

    const useStyles = makeStyles(theme => ({
      root: {
        padding: theme.spacing(3, 2),
        height: 200,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center"
      },
    }));
    

    【讨论】:

    • 考虑到 material-ui 的好解决方案在内部做了很多。另一个“hacky”替代方案是position: absolute; top: 50%; transform: translateY(-50%);
    • contrary,“请注意,vertical-align 仅适用于 inline、inline-block 和 table-cell 元素...”
    【解决方案2】:

    您可以在 MUI v5 中使用Stack。将方向设置为columnjustifyContent 以居中对齐Card 内的内容:

    <Paper component={Stack} direction="column" justifyContent="center">
      <div>
        This content is vertically aligned
      </div>
    </Paper>
    

    现场演示

    【讨论】:

    • 不起作用...即使在您的 CodeSandbox 演示中...
    • @MatthewOakley 它适用于我的密码箱。你使用的是什么浏览器。您使用的是 MUI v5 吗?
    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2021-12-04
    • 2011-07-21
    • 2012-09-07
    • 2014-02-25
    相关资源
    最近更新 更多