元素水平垂直居中的方法

(1)已知高度和宽度的元素解决方案

设置子元素
.item{ position: absolute; top: 50%; left: 50%; margin-top: -75px; /* 设置margin-left / margin-top 为自身高度的一半 */ margin-left: -75px; }

(2)未知高度和宽度元素解决方案

设置子元素
.item{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */
}

(3)使用flex布局实现

设置父元素
.parent{ display: flex; justify-content:center; align-items: center; /* 注意这里需要设置高度来查看垂直居中效果 */ background: #AAA; height: 300px; }

(4)使用table布局实现

设置父元素
.parent{ display: table-cell; text-align:center; vertical-align: middle; /* 注意这里需要设置高度来查看垂直居中效果 */ background: #AAA; height: 300px; }
 
原文地址:https://www.cnblogs.com/zhaodagang8/p/8516782.html