<div class="box">
<text class="info">123</text>
<div class="info"></div>
</div>
已知盒子大小: 1) 子盒子:定位+margin
(position: absolute; left:50%; top:50%; margin-top:-盒子高度一半px;margin-left:-盒子宽度一半px)
.box{
width: 500px;
height: 500px;
background: rgb(216, 185, 185);
position: relative;
}
.info{
width: 120px;
height: 120px;
background: rgb(187, 240, 209);
position: absolute;
left: 50%;
top: 50%;
margin-top: -60px;
margin-left: -60px;
}
2) 子盒子:定位:
positon: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto;
.box{
width: 500px;
height: 500px;
background: rgb(216, 185, 185);
position: relative;
}
.info{
width: 120px;
height: 120px;
background: rgb(187, 240, 209);
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
未知盒子大小:定位+transform
(left:50%;top:50%;transform: translate(-50%,-50%))
.box{
width: 500px;
height: 500px;
background: rgb(216, 185, 185);
position: relative;
}
.info{
width: 120px;
height: 120px;
background: rgb(187, 240, 209);
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%)
}
flex布局: 父盒子
display:flex; justify-content: center; aligin-items: center;
.box{
width: 500px;
height: 500px;
background: rgb(216, 185, 185);
display: flex;
justify-content: center;
align-items: center;
}
.info{
width: 120px;
height: 120px;
background: rgb(187, 240, 209);
}
父盒子:仅用于行内块元素
display: table-ceil; text-align: center; vertical-align: middle;
.box{
width: 500px;
height: 500px;
background: rgb(216, 185, 185);
display: table-cell;
text-align: center;
vertical-align: middle;
}
<div class="box">
<text class="info">123</text>
</div>
使用js获取到盒子的宽高,按照方法1设置 定位+margin
原文:https://www.cnblogs.com/dudududadada/p/13594270.html