transform:translate(-50%,-50%),向左向上,移动自身元素的宽高的一半。 常被用来处理元素水平竖直居中的方案。
即使元素的宽高不确定的情况下,依然适用。
<style>
.box{
position: relative;
width: 300px;
height: 300px;
background-color: #eee;
}
.inner{
width: 200px;
height: 200px;
background-color: #ccc;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* 向左向上 移动自身长宽的50% */
}
</style>
<div class="box">
<div class="inner"></div>
</div>
实现水平垂直居中的效果图如下: