水平居中:
- 行内元素,父级元素设置 text-align: center;
- 块级元素,如果已设置宽高,设置 margin: 0 auto;
- flex布局,display: flex;justify-content: center;
- transform属性,元素设置 position: absolute; left: 50%; transform: (-50%, 0);
- 绝对定位,有固定宽度,position: absolute; left: 0; right: 0; margin: 0 auto;
垂直居中:
- 行内元素,line-height 等于元素高度
- 表格属性,父元素设置 display: table; 元素设置 display: table-cell; vertical-align: middle;
- flex布局,display: flex; align-item: center;
- transform属性,元素设置 position: absolute; top: 50%; transform: (0, -50%);
- 绝对定位,有固定高度,position: absolute; top: 0; bottom: 0; margin: auto 0;
水平垂直居中:
- 绝对定位,有固定宽高,position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;
- 绝对定位,有固定宽高,position: absolute; left: 50%; top: 50%;margin-left: 宽度的一半; margin-top: 高度的一半
- 绝对定位,无宽高,position: absolute; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%);
- flex布局,display: flex; align-item: center; justify-content: center;