容器内元素水平垂直居中

 

<div id="wrap">

  <div id="box">

  </div>
</div>

效果图

方法一

    #wrap{
            width: 300px;
            height: 300px;
            background: lightblue;
            position: relative;
        }
        #box{
            width: 150px;
            height: 150px;
            background: pink;
            position: absolute;
            top:50%;
            left:50%;
            transform: translate(-50%,-50%);
        }

 

方法二

        #wrap{
            width: 300px;
            height: 300px;
            background: lightblue;
            position: relative;
        }
        #box{
            width: 150px;
            height: 150px;
            background: pink;
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom:0;
            margin:auto;
        }    

 

 方法三

        #wrap{
            width: 300px;
            height: 300px;
            background: lightblue;
            position: relative;
        }
        #box{
            width: 150px;
            height: 150px;
            background: pink;
            position: absolute;
            top:50%;
            left:50%;
            margin-left: -75px;
            margin-top: -75px;
        }

方法四

        #wrap{
            width: 300px;
            height: 300px;
            background: lightblue;
            display: flex;
            justify-content:center;
            align-items:center;
        }
        #box{
            width: 150px;
            height: 150px;
            background: pink;
        }

上面四种方法浮动元素均适用

 

posted @ 2018-11-22 20:52  学会谦卑博古  阅读(452)  评论(0编辑  收藏  举报