设定行高(line-height)
<div class="parent">
<div class="child">
</div>
.parent{
width:200px;
height:150px;
border:1px solid #000;
line-height:150px;
text-align:center;
}
.child{
display:inline-block;
width:30px;
height:30px;
background:#c00;
}
使用表格样式
<table>
<tbody>
<tr>
<td class="parent">
<div class="children"></div>
</td>
</tr>
</tbody>
</table>
.parent { text-align: center; }
.children { display: inline-block; }
使用假表格
<div class="parent">
<div class="children"></div>
</div>
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.children {
display: inline-block;
}
使用 absolute + transform
<div class="parent">
<div class="child">
</div>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
使用 absolute + 负margin
<div class="parent">
<div class="child"></div>
</div>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
width: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
height: 100px;
margin-top: -50px;
}
使用 absolute + margin: auto
<div class="parent">
<div class="child">
</div>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
使用flex布局
<div class="parent">
<div class="child">
</div>
.parent{
height: 600px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
border: 1px solid green;
width: 300px;
height:200px
}