css 项目未在简单柔性容器中居中

toiithl6  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(143)

为什么按钮不在中间?我对CSS还是个新手。我了解到align-items使子元素在横轴上居中。我的扣子没扣好。为什么不管用?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>CSS Practice</title>
</head>
<body>
    <input type="button" class="button" value="Get Started"></input>
</body>
</html>
body {
    display: flex;
    align-items: center;
    justify-content: center;
}

.button {
    width: 200px;
    height: 100px;
    display: flex;
    justify-content: center;
}

我不知道发生了什么事。

hkmswyz6

hkmswyz61#

Flex容器的子对象将根据其高度居中。默认情况下,body元素的高度刚好足以包含其内容,因此align-items: center没有可见的效果。将主体的高度设置为视口的高度,以查看输入在屏幕中间居中。

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0; /* prevent scrollbar */
}
6ojccjat

6ojccjat2#

你必须设置main parent的高度,这样你的CSS代码看起来就像这样:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh /* Height of the viewport (window) */
}

.button {
    width: 200px;
    height: 100px;
    display: flex;
    justify-content: center;
}

相关问题