CSS居中DIV包含其他DIV

时间:2015-06-22 21:22:29

标签: html css frontend

如何使用CSS在div中水平居中div?我正在尝试,我让它从左右中心,但我不能让它从顶部和底部居中。

        html {
        height:100%;
    }
    body {
        padding:0px;
        margin: 0px;
        height:100%;
    }
    #openFrame {
        position:fixed;
        top:0px;
        width:100%;
        left:0%;
        height:100%;
    }
    .main {
        position: absolute;
        width: 80%;
        max-height: 100%;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }
    #vid {
        width:100%;
        max-height:100%;
        vertical-align: middle;
    }
    #bottom {
        width:100%;
        height:69px;
        background-color: green;
        background-repeat: no-repeat;
        background-position: top center;
        background-size: contain;
    }
                                                              

1 个答案:

答案 0 :(得分:0)

垂直居中DIV有点棘手。基本上,您必须将position设置为absolute,将容器的position设置为relative。然后将topleft值设置为50%,并通过应用负边距减去要居中的元素宽度/高度的一半。

Codepen example

<!DOCTYPE html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <style type="text/css">
        body, html, #container {
            height: 100%;
            width: 100%;
        }
        #container {
            position: relative;
        }
        #content {
            width: 300px;
            height: 300px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -150px;
            margin-left: -150px;
            background-color: red;
        }
        </style>
    </head>
    <body>
        <div id="container">
            <div id="content"></div>
        </div>
    </body>
</html>