css绝对定位实现垂直居中
2021-03-03
关键是上外边距margin-top。
height: 150px;
position: absolute;
top: 50%;
margin-top: -75px; // 负高度的一半
完整示例:
<div class="container">
<div class="block">Hello World!</div>
</div>
<style>
.container {
width: 400px;
height: 400px;
background-color: yellow;
text-align: center;
position: relative;
}
.block {
width: 60%;
height: 150px;
background-color: red;
display: inline-block;
position: absolute;
left: 20%;
top: 50%;
margin-top: -75px;
}
</style>