html結構:
<div class="parent">
<div class="item"></div>
</div>
1. 已知元素的寬度和高度:
.item {
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px; /* 設置margin-left / margin-top 爲自身高度的一半 */
margin-left: -75px;
}
.item {
position: absolute;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
/* 這個方法可以實現自適應 */
2. 未知元素的高度和寬度:
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 使用css3的transform來實現 */
}
.parent {
display: flex;
justify-content:center;
align-items: center;
background: #AAA;
height: 300px; /* 注意這裏需要設置高度來查看垂直居中效果 */
}