css让一个正方形方块垂直居中

        这里有top和margin-top的区别,top(left,right,bottom)是绝对定位,要用position,margin-top是相对定位,相对于相邻的元素或者父元素。

        代码如下:

        

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>square at center</title>
<style type="text/css">
 #square{
 	 position:absolute;
     top:50%;
     left:50%;
     margin-top:-50px;
     margin-left:-50px;
     100px;
     height:100px;
     background-color:red;
  }
</style>
</head>
<body>
    
      <div id="square">
      </div>

</body>
</html>

  

原文地址:https://www.cnblogs.com/xshang/p/3826363.html