高度不定的div如何垂直水平居中

不问归期 提交于 2020-01-13 02:27:45

面试经常会被问到这个问题,特地总结了下几种方法。

方法1:display: table

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>T</title>
    <style>
        html,body {margin:0; padding:0; height:100%;}
        .a {margin:0 auto; width:800px; height:100%; display:table;}
        .b {display:table-cell; vertical-align:middle;}
        .c {background:#f11;}
        p{height:20px;}
    </style>
</head>
<body>
<div class="a">
    <div class="b">
        <div class="c">
            <br><br><br><br><br><br><br>
            <p></p>
        </div>
    </div>
</div>
</body>
</html>

 

方法2:定位+transform

 .center {
        position: fixed;
        top: 50%;
        left: 50%;
        background-color: #000;
        width:50%;
        height: 50%;
         -webkit-transform: translateX(-50%) translateY(-50%);
        }

<div class="center"></div>

 

方法3:flex布局

.box{
            display: flex;
            justify-content: center;
            align-items: center;
            height:100px;
            border:1px solid red;
        }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!