主要有三种高频的面试考点:一般就会使用margin方法,位移方法,flex布局方法
运行图如图所示:
(1)margin方法
css书写
<style>
.father {
position: relative;
width: 300px;
height: 300px;
margin: 50px auto;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
width: 120px;
height: 120px;
margin-left: -60px; //右移和上移自己的宽高的50%
margin-top: -60px;
background-color: blue;
}
</style>
html书写(三种html书写方式一致,以下省略,不再进行书写)
<div class="father">
<div class="son"></div>
</div>
(2)位移方法
css书写
<style>
.father {
position: relative;
width: 300px;
height: 300px;
background-color: Pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); //右移和上移自己的宽高的50%
width: 120px;
height: 120px;
background-color: blue;
}
</style>
(3)flex布局方法
css书写
<style>
.father {
display: flex;
align-items: center; //y轴变化,默认为侧轴
justify-content: center; //x轴,默认为主轴
width: 300px;
height: 300px;
background-color: Pink;
}
.son {
width: 120px;
height: 120px;
background-color: blue;
}
</style>