方法一
1.当使用position定位,margin-top、margin-left水平垂直居中时,先利用top:50%、left:50%将子盒子的左上角定位到父盒子的正中,然后使用margin-top:50%;margin-left:50%,完成。
//HTML、css
<style>
/* * {
padding: 0;
margin: 0;
} *//*去掉所有元素内外边距
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
/* margin-top: auto; */
/*浏览器设置的上边距*/
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: purple;
margin-top: -50px;
margin-left: -50px;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
方法二
2.利用transform:translate(x,y)
// HTML、css
<style>
/* * {
padding: 0;
margin: 0;
} */
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
}
.son {
position: absolute;
/* margin-top: auto; */
/*浏览器设置的上边距*/
top: 50%;
left: 50%;
width: 100px;
height: 100px;
background-color: purple;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
方法三
3.使用弹性布局(flex)
// HTML、css
<style>
/* * {
padding: 0;
margin: 0;
} */
.father {
position: relative;
width: 500px;
height: 500px;
background-color: pink;
display: flex;
justify-content: center;
align-items: center;
}
.son {
position: absolute;
/* margin-top: auto; */
/*浏览器设置的上边距*/
width: 100px;
height: 100px;
background-color: purple;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>