方法一:定位法
html结构:
<div class="parent">
<div class="children">
</div>
</div>
css样式:
.parent{
width:500px;
height:500px;
background:#ccc;
position: relative;
}
.children{
width:300px;
height:300px;
background: red;
position: absolute;
top:0;
bottom:0;
left: 0;
right:0;
margin: auto;
}
效果图:
方法二:table-cell方法
html结构:
<div class="parent">
<div class="children">
</div>
</div>
css样式:
.parent{
width:500px;
height:500px;
background:#ccc;
display: table-cell;
vertical-align: middle
}
.children{
width:300px;
height:300px;
background: red;
margin:auto;
}
效果图:
方法三:弹性布局方法
html结构:
<div class="parent">
<div class="children">
</div>
</div>
css样式:
.parent{
width:500px;
height:500px;
background:#ccc;
display: flex;
justify-content: center;
align-items: center;
}
.children{
width:300px;
height:300px;
background: red;
}
效果图: