通用html代码
<div class="wrap">
<div class="content">
</div>
</div>
css代码
方案1 transform:translate设置 -50%
.wrap {
margin:0 auto;
background-color: yellow;
width: 300px;
height: 300px;
position: relative;
}
.content {
background-color: #ddd;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
line-height: 100px;
text-align: center;
}
方案2 flex布局
.wrap {
margin: 0 auto;
background-color: #ddd;
width: 300px;
height: 300px;
display: flex;
justify-content: center;//使子项目水平居中
align-items: center;//使子项目垂直居中
}
.content {
background-color: red;
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
}
方案3 父元素设置为:position: relative; 子元素设置为:position: absolute;
距上左50%,然后设置margin-top;margin-left的值为元素本身宽高的二分之一的负值。
.wrap {
position: relative;
width: 300px;
height: 300px;
background: red;
margin: 0 auto;
}
.content {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
line-height: 100px;//本盒子的高度
margin-left:-50px;//本盒子宽度的-1/2
margin-top:-50px;//本盒子高度的-1/2
background: #ddd;
text-align: center;
vertical-align: middle;
}