绝对定位的盒子水平/垂直居中

普通的盒子是左右margin 改为 auto就可, 但是对于绝对定位就无效了

定位的盒子也可以水平或者垂直居中,有一个算法。

  1. 首先left 50% 父盒子的一半大小

  2. 然后margin-left的值设为负数的自己盒子宽度的一半值就可以了

    另外可以使用CSS3的translate来做更方便,避免了人工计算

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <style>
    .box {
    width: 499.9999px;
    height: 400px;
    background: pink;
    position: absolute;
    left:50%;
    top:50%;
    /* margin-left: -250px; */
    transform:translate(-50%,-50%); /* 走的自己的一半 */
    }
    </style>
    <body>
    <div class="box"></div>
    </body>