<style>
.dad{
background: #c5ebfa;
width: 300px;
height: 300px;
position: relative;
}
.son{
width: 50px;
height: 50px;
background: #feb9bf;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="dad">
<div class="son"></div>
</div>
<style>
.dad{
background: #c5ebfa;
width: 300px;
height: 300px;
position: relative;
}
.son{
width: 50px;
height: 50px;
background: #feb9bf;
position: absolute;
top: 50%;
left:50%;
margin-left:-25px;
margin-top:-25px;
// 或者:
// transform: translate(-50%,-50%);
}
</style>
<div class="dad">
<div class="son">
我是son元素
</div>
</div>
- flex布局
<style>
.dad{
background: #c5ebfa;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.son{
/*width: 50px;*/
/*height: 50px;*/
background: #feb9bf;
}
</style>
<div class="dad">
<div class="son">
我是son元素
</div>
</div>