(注:类名为dad的为父容器,类名为son的为完美居中容器)
一、需要居中的盒子已知宽高。
(1)使用绝对定位。
① 用绝对定位先移动50%,再利用margin往回移动宽高的一半。
② 用绝对定位先将上下左右的值都设为0,再将margin设为auto.
③ 使用绝对定位,搭配calc( 50% - 宽高的一半 )。
二、需要居中的盒子未知宽高。
(1)使用绝对定位。
① 先使用绝对定位移动50%,再设置 transform: translate(-50%, -50%);
(2)使用flex布局。
① 父容器设置 display: flex; 子容器设置 margin: auto;
② 父容器设置 display: flex; justify-content: center; align-items: center;
(注:这种方法无论居中元素的宽高是否已知,均适用!)