简体   繁体   中英

How to align two div horizontally and vertically in middle of page with header and footer?

I am designing a new page using Bootstrap 4. There are 4 elements in the page header, footer and two content boxes(divs). Header and footer will remain at top and bottom respectively (using default bootstrap classes for them) but i want both content boxes should appear in middle of the page both horizontally and vertically regardless of the screen size. One content box beneath the another with space between them. You can refer attached picture for same.

I have tried using flex class of bootstrap but it didn't work out much. 在此处输入图片说明

There's a lot of approaches to get this solution. That's a simple one:

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%);
}

Result

Divs centered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM