实现上方效果,下面列举几个常用的方法,个人比较推荐用flex布局实现
方式1(利用margin和绝对定位)
html
<div class="container">
<div class="box"></div>
</div>
css
.container {
position: relative;
width: 150px;
height: 150px;
background-color: #000;
.box {
margin: auto;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 50px;
height: 50px;
background-color: #fff;
}
}
方式2(利用flex布局)
html
<div class="container">
<div class="box"></div>
</div>
css
.container {
position: relative;
width: 150px;
height: 150px;
background-color: #000;
display: flex;
justify-content: center;
align-items: center;
.box {
width: 50px;
height: 50px;
background-color: #fff;
}
}