1 水平居中
margin: 0 auto;
2 水平垂直居中
(1)方法一 (定位,top和left偏移量50%,再各进行本身的负向偏移50%)
position: relative; /* 如果定位为绝对定位,那么父元素设置相对定位*/
width: 400px;
height: 200px;
top: 50%;
left: 50%;
margin: -100px 0 0 -200px; /* ① 需要知道div的宽高*/
/* transform: translate(-50%, -50%); */ /* ② (变换-平移)不需要知道div的宽高*/
① margin: -100px 0 0 -200px;
需要知道div的宽高
② transform: translate(-50%, -50%);
(变换-平移)不需要知道div的宽高
(2)方法二 flex布局 (主轴和交叉轴上对齐都设为center)
display: flex;
align-items: center;
justify-content: center;
(3) 方法三 绝对定位+margin: auto
position: absolute; /* 绝对定位 */
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;