首页 > 解决方案 > Flexbox 不会将 div 对齐到屏幕中心

问题描述

这是我第一次使用堆栈溢出,所以请多多包涵。我遇到的问题是当我尝试将我的 div 对齐到屏幕的中心时,由于某种原因它不起作用。我到处研究以尝试找到解决方案,但它不起作用。有谁知道问题是什么?

body{
    margin: 0;
    background-image: linear-gradient(to top, rgba(14, 245, 26, 0.829), rgb(0, 102, 255));
    background-attachment: fixed;
}

.container{
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
}
<!DOCTYPE html>
<html>
    <head>
        <title>Super Cool Calculator</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div id="heading">
                <h3>The Great Calculator</h3>
                <h4>By Antdog0101</h4>
            </div>
        </div>
    <script src="script.js"></script>
    </body>
</html>

这是我保存代码时的结果: https ://i.stack.imgur.com/I1dRl.png

标签: htmlcss

解决方案


你只需要在 css 中添加这个:

html, body {
    height: 100%;
}

并在:

    .container {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    height:100%;
    }

推荐阅读