css绝对定位的盒子居中算法

绝对定位的盒子居中

加了绝对定位的盒子不能通过margin:0 auto水平居中,但是可以通过以下方法实现水平居中。

①left:50%;让盒子的左侧移动到父级元素的水平中心位置
②margin-left:-100px;让盒子向左移动自身宽度的一半。

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title></title>
  <style type="text/css">
    .box {
      position: absolute;
      left: 50%;
      margin-left: -100px;
      width: 200px;
      height: 200px;    
      background-color: pink;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
</html>
posted @ 2020-08-06 19:59  珊迪·奇克斯  阅读(561)  评论(0编辑  收藏  举报