适用范围
仅居中元素定宽高适用
- absolute + 负margin
- absolute + margin auto
- absolute + calc
居中元素不定宽高
- absolute + transform
- flex
定义的盒子如下
<div class="wp">
<div class="box size">123123</div>
</div>
.wp {
position: relative;
width: 300px;
height: 300px;
border: 1px solid red;
}
.size {
width: 100px;
height: 100px;
background: green;
}
absolute + 负margin
.wp {
position: relative;
}
.box {
position: absolute;;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
absolute + margin auto
.wp {
position: relative;
}
.box {
position: absolute;;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
absolute + calc
.wp {
position: relative;
}
.box {
position: absolute;;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
absolute + transform
.wp {
position: relative;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
flex
.wp {
display: flex;
justify-content: center;
align-items: center;
}