CSS实现水平垂直居中

187
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>一个200*200的div在不同分辨率屏幕上下左右居中,用css实现</title>

  <style>
    *{
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    .main{
      height: 400px;
      width: 400px;
      background-color: rebeccapurple;
      
      /* 第一种居中方式 */
      /* position: absolute;
      left: 50%;
      top: 50%;
      transform:translate(-100px,-100px);  */
      
      /* 第二种居中方式 */
      /* position: absolute;
      left: 50%;
      top: 50%;
      margin-left:-100px;
      margin-top:-100px; */
      
      /* 第三种居中方式 */
      /* position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
      margin:auto;  */
      
      /* 第四种居中方式(但是要写在父元素里面哟) */
      /* display: table-cell;
      vertical-align: middle;
      text-align: center; */
      
      /* 
      ** 第五种居中方式(但是要写在父元素里面哟)
      ** 一定要绝对定位以后才会实现height: 100%;
      */
      /* height: 100%;
      width: 100%;
      background-color:rebeccapurple;
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;  */
     
    }

    .child{
      width: 200px;
      height: 200px;
      background-color: red;
      margin: 0 auto; 
    }

  </style>
</head>
<body>
  <div class="main">
    <div class="child">a</div>
  </div>
</body>
</html>