一、水平居中
- 文本居中:
text-align: center;
- flex布局
(1)容器:flex-direction: row; justify-content: center;
,flex-direction: column; align-items: center;
(2)项目:根据容器的主轴方向,选择justify-self: center;
或者align-self: center;
二、垂直居中
- 行内元素文本垂直居中:
vertical-align: middle;
- 块级元素文本垂直居中:
height: x; line-height: x;
- flex布局
(1)容器:flex-direction: row; align-items: center;
,flex-direction: column; justify-content: center;
(2)项目:根据容器的主轴方向,选择justify-self: center;
或者align-self: center;
三、比较通用的方法设置居中
-
设置
position
(1)相对浏览器:设置positon: fixed
(2)相对父元素:设置position: absolute
或position: relative
(父元素为position: static
时选择后者) -
设置
margin
(1)预处理1:若是元素脱离了文本流(失去了block
或者inline-block
的流特性),需要进行预处理操作使得元素在需要对齐的方向上重新具有流特性。没有流特性的元素,无法使用auto
来自动计算margin
。/* 设置left, right属性可以让元素在水平方向上恢复流特性 */ left: 0; right: 0; /* 设置top, bottom属性可以让元素在垂直方向上恢复流特性 */ top: 0; bottom: 0;
(2)预处理2:水平居中需要元素设置
width
,垂直居中需要元素设置height
。这样才能通过auto
为元素自动计算margin
。(3)设置
margin: auto;
(水平垂直对齐)、margin: 0 auto;
(水平对齐)、margin: auto 0;
(垂直对齐)