子盒子,在父盒子里面水平居中和垂直居中的方法归纳

177 阅读1分钟

方法一:margin

1.通过定位(子绝父相),给父盒子设置相对定位,子盒子设置绝对定位
2.让子盒子往右移动父盒子的一半,往下移动父盒子的一半
3.子盒子使用margin-left,margin-top负子盒子宽度的一半
缺点:子盒子宽度变化后需要重新修改代码

<style>
    .father {
      position: relative;
      width: 500px;
      height: 500px;
      background-color: pink;
    }

    .son {
      position: absolute;
      left: 50%;
      top: 50%;
      margin-left: -150px;
      margin-top: -150px;
      width: 300px;
      height: 300px;
      background-color: skyblue;
    }
  </style>

方法二:transform

1.通过定位(子绝父相),给父盒子设置相对定位,子盒子设置绝对定位
2.让子盒子往右移动父盒子的一半,往下移动父盒子的一半
3.子盒子使用transform:translate(-50%,-50%);沿X轴Y轴负方向移动自己宽高的一半
优点:子盒子宽度变化不需要更改代码

<style>
   .father {
     position: relative;
     width: 500px;
     height: 500px;
     background-color: pink;
   }

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

方法三:margin: auto;

1.通过定位(子绝父相),给父盒子设置相对定位,子盒子设置绝对定位
2.盒子定位时,top,left,right,bottom都设置为0,并且设置margin: auto;

<style>
    .father {
      position: relative;
      width: 500px;
      height: 500px;
      background-color: pink;
    }

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

方法四:flex

.father{
  display: flex;
  justify-content: center;
  align-items: center;}