一. 先介绍下定位
绝对定位:相对于最近一级的祖元素而言,不占有位置
绝对定位:相对于自己当前的位置而言,占有位置
口诀:父相子绝
二.在介绍一下2D
transform: translateX(-50%);
transform: translatey(-50%);
相对于自身的宽度和高度移动
代码演示:
* {
margin: 0px;
padding: 0px;
}
.father {
position: relative;
width: 300px;
height: 300px;
background-color: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: powderblue;
}
方法二:利用flex布局进行
.father {
width: 300px;
height: 300px;
background-color: rosybrown;
display: flex;
align-items: center;
justify-content: center;
}
.son {
width: 100px;
height: 100px;
background-color: powderblue;
}