一个定位的子盒子在父盒子中水平垂直居中的方法

371 阅读2分钟

一个子盒子在父盒子中水平垂直居中的方法一共有3种.

html结构如下:

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

第一种 使用margin移动到合适的位置

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

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

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

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

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

第二种 使用位移

这个方法在第一个基础上简化了margin部分

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

.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;
    }

使用这个方法需要注意

  • translate平移,百分比取值是参照盒子自己本身

  • 使用transform属性,一定要注意样式层叠!!!避免样式被覆盖

第三种

这种方法是很早之前写代码实现盒子水平垂直居中的一种办法

.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;
    } 

设置四个方位的偏移量值全部为0

其中margin:auto;意思是表示四周全部自动充满; 结合参考下面的左右auto便于理解.

/*左侧全部充满 */
margin-left: auto;
/* 右侧全部充满 */
margin-right: auto;