首页 > 解决方案 > 使用 Flexbox 和 Material UI 在页面上居中表单

问题描述

试图居中对齐按钮。我还将在该区域放置一个表单,因此我需要一个位于页面中间的盒子或容器。现在由于某种原因,即使我指定了 100% 的最大高度和宽度,按钮也是居中的,这很好,但仍然位于最顶部。

我可能还需要一个额外的盒子来充当我假设的根盒子内的表单内容的容器。

我不确定我是否指定了正确的属性名称,alignItems因为这是样式对象,例如,您不能将align-items其用作道具。

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

const useStyles = makeStyles({
    root: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        height: '100%'
    },
    button: {
        background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
        border: 0,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        padding: '0 30px'
    }
});

function Login() {
    const classes = useStyles();
    return (
        <Box className={classes.root}>
            <Button className={classes.button}>Login</Button>
        </Box>
    );
}

export default Login;

在此处输入图像描述

标签: cssreactjsflexboxmaterial-ui

解决方案


这将是因为您的“根”类位于 Box 组件上 - 这将需要其父级指定高度 - 否则它将无法将自己的高度调整为 100% - 或者换句话说 - 元素具有100% 的高度 - 但 100% 是什么?

尝试将 html、body 和任何其他父元素设置为具有高度。

html, body {
  height: 100%;
  width: 100%;
  overflow: hidden
}
.root {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
    }
    .button {
        background: linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%);
        border: 0;
        border-radius: 3;
        box-shadow: 0 3px 5px 2px rgba(255, 105, 135, .3);
        color: white;
        height: 48;
        padding: 0 30px;
    }
<Box class="root">
    <Button class="button">Login</Button>
</Box>


推荐阅读