一、水平居中
- 子元素是行内元素,父元素是块元素[父]:
text-align: center
- 子元素是块级元素(已知宽度)[子]:
margin: 0 auto
- 设置父元素为相对定位[子]:
absolute + transform
position: absolute;
left: 50%;
transform: translateX(-50%);
- 父元素添加:
flex + justify-content:center
二、垂直居中
- 单行的行内元素[子]:
line-height: height
- 设置父元素为相对定位[子]:
absolute + transform
position: absolute;
top: 50%;
transform: translateY(-50%);
- 父元素添加:
flex + align-items: center
三、水平垂直居中
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
- 设置父元素为相对定位[子]:
absolute + transform
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
- 父元素添加:
flex + justify-content + align-items