2d变换
平移
transform
- translate(x,y)
- translateX()
- translateY()
- 数值
- 百分比
- 不脱离文档流
- 支持负值
- translate(100px)只写一个值只有x轴平移
<style>
.father {
width: 300px;
height: 300px;
background-color: pink;
margin: 100px auto;
}
.son {
width: 100px;
height: 100px;
background-color: blue;
transition: 2s;
}
.other {
width: 100px;
height: 100px;
background-color: yellow;
}
.father:hover .son {
/* 以元素最左侧为圆心,画两条坐标轴,x轴向右边100px,y轴向下边100px*/
transform: translate(100px, 100px);
transform: translate(-100px, -100px);
/* 沿着x轴平移 */
transform: translateX(100px);
/* 沿着y轴平移 */
transform: translateY(100px);
/* 沿着x轴和y轴平移 */
transform: translateX(100px) translateY(100px);
/* 百分比 参考元素自身的宽高 */
transform: translate(100%, 100%);
/* 如果translate()只写一个值,表示另一个为0 */
transform: translate(100px);
}
</style>
<div class="father">
<div class="son"></div>
<div class="other"></div>
</div>
元素水平垂直居中案例
方法: 使用2d平移
特点: 不需要知道父元素的宽高
子绝父相
2d平移
<style>
.father {
width: 300px;
height: 400px;
margin: 50px auto;
background-color: pink;
position: relative;
}
.son {
width: 200px;
height: 100px;
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
/* margin-top: -50px;
margin-left: -100px; */
/* translate的百分比参考元素自身的宽高 */
transform: translate(-50%, -50%);
}
</style>