首页 > 解决方案 > 如何将页面中间的两个div与页眉和页脚水平和垂直对齐?

问题描述

我正在使用 Bootstrap 4 设计一个新页面。页眉、页脚和两个内容框(div)中有 4 个元素。页眉和页脚将分别保留在顶部和底部(使用它们的默认引导类),但我希望无论屏幕大小如何,两个内容框都应水平和垂直显示在页面中间。一个内容框在另一个内容框下方,它们之间有空间。您可以参考所附图片。

我曾尝试使用 flex 类的引导程序,但效果不佳。在此处输入图像描述

标签: htmlcssbootstrap-4

解决方案


有很多方法可以得到这个解决方案。这是一个简单的:

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
          crossorigin="anonymous"
        />
        <link rel="stylesheet" href="css/style.css" />
        <title>Document</title>
    </head>
    <body>
        <header class="container-fluid">HEADER</header>

        <main>
            <div class="center">
                <div id="container-1" class="">DIV 1</div>
                <div id="container-2" class="">DIV 2</div>
            </div>
        </main>
        <footer class="container-fluid">FOOTER</footer>
    </body>
</html>

CSS

header {
    background-color: red;
}

body {
    margin-bottom: 60px; /* Margin bottom by footer height */
}

footer {
    background-color: green;
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 60px; /* Set the fixed height of the footer here */
    line-height: 60px; /* Vertically center the text there */
}

#container-1 {
    padding: 100px;
    margin-bottom: 150px;
    background-color: yellow;
}

#container-2 {
    padding: 100px;
    background-color: blue;
}

.center {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

结果

以 div 为中心


推荐阅读