实现目标:实现元素居中
实现方法:CSS定位

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <link rel="stylesheet" href="../css/index.css" type="text/css">
  6. </head>
  7. <body>
  8. <div class="wrapper">
  9. <div class="box"></div>
  10. </div>
  11. </body>
  12. </html>
.wrapper{
    position: relative;
    width: 200px;
    height: 200px;
    background-color: orange;
    margin-left: 100px;
}


.box{
    width: 50px;
    height: 50px;
    background-color: green;
}

image.png
如上图所示,现在我们想要让绿色方块的位置在橙色方块居中显示。

.box{
    width: 50px;
    height: 50px;
    background-color: green;
    position: absolute;
    left: 50%;
    top: 50%;
}

image.png
我们可以给绿色方块加上定位属性absolute,让他的left跟top设置为50%。但是我们发左顶点式剧中了,这并不是我们想要的效果。

.box{
    width: 50px;
    height: 50px;
    background-color: green;
    position: absolute;
    left: 50%;
    top: 50%;
      /*给方块加上margin,margin的值为方块宽/高的一半*/
    margin-top: -25px;
    margin-left: -25px;  
}

image.png
这样就实现方块居中了

总结:

1 设置定位属性
2 left/top 设置为50%
3 margin-top 为 负的 元素高度的一半
4 margin-left 为 负的 元素宽度的一半