乐趣区

css实现水平居中的4种方法

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; /* 注意这里需要设置高度来查看垂直居中效果 */
}

退出移动版