不定宽高水平且垂直居中的实现方法
flex布局
效果预览
<div class="parent">
<div class="child">水平垂直居中</div>
</div>
div.parent {
display: flex;
justify-content: center;
align-items: center;
background: #EDEDED;
width: 800px;
height: 400px;
}
div.child {
background: green;
}
预览地址
<div class="parent">
<div class="child">水平垂直居中</div>
</div>
div.parent {
position: relative;
width: 800px;
height: 300px;
background: #EDEDED;
}
div.child {
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
table-cell
效果预览
<div class="parent">
<div class="child">水平垂直居中</div>
</div>
div.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
background: #EDEDED;
width: 300px;
height: 300px;
}
div.child {
display: inline-block;
background: green;
}