水平垂直居中的——万能好用方法

一、absolute方法

HTML代码如下:

<body>
        <div id="box">
            <div class="circle left"></div>
            <div class="circle right"></div>
        </div>
</body>

css如下:

#box{
            width: 400px;
            height: 200px;
            background: #ccc;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            overflow: hidden;
        }

box是子元素,box相对于body垂直水平居中,只要在box添加以上代码就可以了

 

 

二、display:flex

css如下:

body{
    height: 100vh;
    display: flex;
     justify-content: center;
     align-items: center;   

}
        
#box{
    width: 400px;
    height: 200px;
    background: #ccc;
        position: relative;
}    

在父元素上加以上代码就可以使元素自适应的居中

 

效果

posted @ 2017-06-04 20:44  Lu_Lu陌鹿  阅读(259)  评论(0编辑  收藏  举报