flex
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container{
width: 100%;
height: 500px;
display: flex; //默认row方向
justify-content: center; //平行row方向居中对齐
align-items: center; //垂直row方向居中对齐
background-color: antiquewhite;
}
.box{
width: 50px;
height: 50px;
background-color: red;
}
绝对定位
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container{
width: 100%;
height: 500px;
background-color: antiquewhite;
position: relative;
}
.box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
absolute + transform
html:
<div class="container">
<div class="box"></div>
</div>
css:
.container{
width: 100%;
height: 500px;
background-color: antiquewhite;
position: relative;
}
.box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
absolute + calc
html;
<div class="container">
<div class="box"></div>
</div>
css:
.container{
width: 100%;
height: 500px;
background-color: antiquewhite;
position: relative;
}
.box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 25px);
}