基本样式:
<style>
.box{
width: 400px;
height: 400px;
margin-top: 10px;
background-color: blue;
color: #fff;
}
.wrapper{
background-color: red;
}
</style>
<div class="box" id="target">
<div class="wrapper">未知宽高的div元素</div>
</div>
position + translate方式
给class=box的父元素添加类名position-translate-box
.position-translate-box{
position: relative;
}
.position-translate-box .wrapper{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用table-cell
给class=box的父元素添加类名table-cell-box
.table-cell-box{
display: table-cell;
vertical-align: middle;
text-align: center;
}
.table-cell .wrapper{
display: inline-block;
}
使用flex布局
给class=box的父元素添加类名flex-box
.flex-box{
display: flex;
justify-content: center;
align-items: center;
}