1、效果图
2、代码
01、盒子宽高不固定
<style>
.clearfix:after {
content: "";
display: block;
clear: both;
}
.box1{
width: 300px;
height: 300px;
background-color: #f0f0f0;
margin: 10px;
float: left;
position: relative;
}
.box1-center {
padding:10px;
background:#3FC9C1;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /*往上(x轴),左(y轴)移动自身长宽的 50%*/
}
</style>
<div class="clearfix">
<!--盒子宽高不固定-->
<div class="box1">
<div class="box1-center">center</div>
</div>
</div>
02、知道盒子宽高的情况
<style>
.clearfix:after {
content: "";
display: block;
clear: both;
}
.box2 {
width: 300px;
height: 300px;
background-color: #f0f0f0;
margin: 10px;
float: left;
position: relative;
}
.box2-center{
width:80px;
height:80px;
line-height:80px;
text-align:center;
background:#3FC9C1;
position: absolute;
top: 50%;
left: 50%;
margin-top: -40px; /* 自身 height 的一半 */
margin-left: -40px; /* 自身 width 的一半 */
}
</style>
<!--盒子固定宽高-->
<div class="box2">
<div class="box2-center">center</div>
</div>