1. 使用 Flex
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent{
height: 300px;
width: 300px;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.child{
background: red;
height: 100px;
width: 100px;
}
2. 绝对定位 + margin: auto
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent{
height: 300px;
width: 300px;
border: 1px solid black;
position: relative;
}
.child{
background: orange;
position: absolute;
height: 100px;
width: 100px;
margin: auto;
left: 0;
top: 0;
bottom: 0;
right: 0;
}
将子元素相对于父元素绝对定位后,上下左右设为0,再将子元素的 margin 设为 auto,子元素就会被挤到父元素中央。
3. 绝对定位 + transform
HTML
<div class="parent">
<div class="child"></div>
</div>
CSS
.parent{
height: 300px;
width: 300px;
border: 1px solid black;
position: relative;
}
.child{
position: absolute;
background: yellow;
height: 100px;
width: 100px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
translate 偏移的百分比是以元素自身的尺寸为基准的。
4. 绝对定位 + 负外边距
HTML
<div class="parent">
<div class="child"></div>
</div>
.parent{
height: 300px;
width: 300px;
border: 1px solid black;
position: relative;
}
.child{
position: absolute;
background: blue;
height: 100px;
width: 100px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
注意:该方法需要提前知道被居中元素的尺寸才可以精确实现垂直居中。
5. 使用 table 或 装成 table
真的 table
HTML
<table class="parent">
<tr>
<td>
<div class="child">
table
</div>
</td>
</tr>
</table>
CSS
.parent{
border: 1px solid black;
text-align:center;
width: 300px;
height: 300px;
}
.child{
margin: 0 auto;
width: 100px;
height: 100px;
background: lightgreen;
color: white;
line-height: 100px;
}
伪装的 table
HTML
<div class="table">
<div class="td">
<div class="content">
伪装的table
</div>
</div>
</div>
CSS
.table{
display: table;
border: 1px solid black;
height: 300px;
width: 300px;
text-align: center;
}
.td{
display: table-cell;
vertical-align: middle;
}
.content{
margin: 0 auto;
width: 100px;
height: 100px;
background: green;
color: white;
line-height: 100px;
}