盒子居中的方法

162 阅读1分钟

html结构

<div class="father">
   <div class="son"></div>
</div>

  1. 使用margin移动到合适的位置

这个方法之前学习定位的时候有提到过,先分别给子盒子设置向左和向下父盒子的一半

这个时候我们会发现,子盒子并没有处于水平垂直居中的位置,而是处于父盒子靠右下角地方

因为这样是让son这个盒子的左上角在father这个盒子的正中心.

所以,需要再使用margin-left和margin-top让son盒子分别向左和向上移动自身宽高的一半,且为负值.

.father {
      position:reletive;
      width:300px;
      height:300px;
    }
.son {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left:-100px;
      margin-top:-50px;
      width: 200px;
      height: 100px;
      background-color: skyblue;
    }

  1. 使用位移 这个方法在第一个基础上简化了margin部分

优点 当son盒子宽高改变时,不用做其他改变,仍然居中 避免使用margin时会出现小数的情况

使用这个方法需要注意 translate平移,百分比取值是参照盒子自己本身 使用transform属性,一定要注意样式层叠,避免样式被覆盖

.father {
      position:reletive;
      width:200px;
      height:200px;
    }
.son {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 100px;
      height: 100px;
      background-color: skyblue;
    }

  1. 定位 设置四个方位的偏移量值全部为0 其中margin:auto;意思是表示四周全部自动充满
.father {
      position:reletive;
      width:300px;
      height:300px;
    }
.son {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 200px;
      height: 200px;
      background-color: skyblue;
    } 

4.flex

.father {
      width:300px;
      height:300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }