水平居中和transform: translateY(-50%) 实现元素垂直居中
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>垂直居中</title><style>* {margin: 0;padding: 0;}.center {width: 960px;height: 500px;margin: 0 auto;background: green;}.center p {background: #fff;position: relative;top: 50%;transform: translateY(-50%);left: 0;right: 0;margin: 0 auto;width: 100px;}</style></head><body><div class="center"><p>垂直居中内容</p></div></body></html>
原理 transform: translateY(-50%); 让div 沿Y轴平移自身高度的一半
<div class="wrapper"><div class="conten"></div></div>
.wrapper{position: relative;width: 300px;height: 300px;border: 1px red solid;}.conten{position: absolute;width: 100px;height: 100px;left:50%;top:50%;transform:translate(-50%,-50%);border: 1px green solid;}
<div class="box"><div class="wrapper"><div class="conter"></div></div></div>
.box{display:table;}.wrapper{width: 300px;height: 300px;border: 1px red solid;display: table-cell;text-align: center;vertical-align: middle;}.conter{width: 100px;height: 100px;display: inline-block;border: 1px green solid;}
<div class="wrapper"><div class="conter"></div></div>
.wrapper{width: 300px;height: 300px;border: 1px red solid;display: flex;justify-content:center;align-items:center;}.conter{width: 100px;height: 100px;border: 1px green solid;}