使用 Material-UI 纸垂直对齐

Men*_*les 11 reactjs material-ui

我想在 Material-UI Paper 组件中垂直对齐一些文本。

代码在这里:https : //codesandbox.io/embed/material-demo-fz9wj

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;
Run Code Online (Sandbox Code Playgroud)

Arn*_*ist 16

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

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

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

  • 考虑到 material-ui 的好解决方案在内部做了很多。另一个“hacky”选择是`position: absolute; 顶部:50%;变换:translateY(-50%);` (3认同)

Nea*_*arl 5

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

<Paper component={Stack} direction="column" justifyContent="center">
  <div>
    This content is vertically aligned
  </div>
</Paper>
Run Code Online (Sandbox Code Playgroud)

现场演示

Codesandbox 演示