1 单行文本居中
- 水平居中:text-align:center;
- 垂直居中:line-height:100px; (line-height的值=height的值一致)
2 多行文本的垂直居中
- 父元素:display: table
- 子元素:display: table-cell; vertical-align: middle;
3 absolute与transform配合实现
给子元素设置以下内容
-
绝对定位:position:absolute; left:50%;top:50%;
-定位至相对其距离最近的具有定位属性的父元素的宽高一半的位置。 -
位移:transform:translate(-50%,-50%);
-让元素相对自己原来的位置,向上位移高度的一半,向左位移宽度的一半。
4 flex实现
给父元素添加属性:
display:flex;
align-items: center;
justify-content: center;
5 absolute之top left right bottom 方式
先给元素设置绝对定位,再依次添加以下属性,具体代码如下所示。
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
6 table-cell方式
给父元素添加以下属性:
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px;
height: 300px;
7calc() 函数
给子元素添加以下属性:
position: absolute;
top:calc(50% - 100px); // calc(50% - 元素本身高度一半)
left: calc(50% - 150px); // 注意使用时减号间有空格
width: 200px;
height: 300px;