水平垂直居中应该这样答!

133 阅读1分钟

如何让子盒子在父盒子内水平垂直居中显示?

<!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>Document</title>
  </head>
  
  <style>
    .father {
      width: 600px;
      height: 600px;
      margin: 150px auto;
      background-color: red;
    }
    
    .son {
      width: 300px;
      height: 300px;
      background-color: #000;
    }
  </style>
  
  <body>
    <div class="father">
      <div class="son"></div>
    </div>
  </body>
  
</html>

利用子绝父相,先将元素的左上角通过top:50%和left:50%定位到页面的中心,然后再通过translate来调整元素的中心点到页面的中心

<style>
  .father {
    position: relative;
    width: 600px;
    height: 600px;
    margin: 150px auto;
    background-color: red;
  }

  .son {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 300px;
    background-color: #000;
    transform: translate(-50%, -50%);
  }
</style>

利用子绝父相,设置四个方向的值都为0,并将margin设置为auto,由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中。该方法适用于盒子有宽高的情况

<style>
  .father {
    position: relative;
    width: 600px;
    height: 600px;
    margin: 150px auto;
    background-color: red;
  }

  .son {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 300px;
    height: 300px;
    margin: auto;
    background-color: #000;
  }
</style>

利用子绝父相,先将元素的左上角通过top:50%和left:50%定位到页面的中心,然后再通过margin负值(注意:margin调整的值应该是子盒子宽高的一半而不是父盒子的一半)来调整元素的中心点到页面的中心。该方法适用于盒子宽高已知的情况

<style>
  .father {
    position: relative;
    width: 600px;
    height: 600px;
    margin: 150px auto;
    background-color: red;
  }

  .son {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300px;
    height: 300px;
    margin-top: -150px;  /* 自身高度的一半 */
    margin-left: -150px; /* 自身宽度的一半 */
    background-color: #000;
  }
</style>

父元素使用flex布局,通过align-items:center和justify-content:center设置容器的垂直和水平方向上为居中对齐,然后它的子元素也可以实现垂直和水平的居中

<style>
  .father {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 600px;
    height: 600px;
    margin: 150px auto;
    background-color: red;
  }

  .son {
    width: 300px;
    height: 300px;
    background-color: #000;
  }
</style>