1. 利用table cell的特性使用vertical:midlle 进行辅助
.wrap {
width: 600px;
height: 600px;
display: table-cell;
vertical-align: middle;
text-align: center;
background: #92b922;
}
.inner {
background: #de3168;
display: inline-block;
color: #fff;
padding: 20px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner">
Hello I'm here
</div>
</div>
2.利用CSS transform 进行居中(其中百分比是指当前元素 content+ padding + border的大小)
<style>
.parent{
position: relative;
height:300px;
width: 300px;
background: #FD0C70;
}
.parent .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<div class="parent">
<div class="child">hello I'm here</div>
</div>
3. 利用flex 布局
<style>
.parent{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height:300px;
background: #FD0C70;
}
.parent .child{
color: #fff;
}
</style>
<div class="parent">
<div class="child">hello I'm here</div>
</div>