transform 转换
转换 transform 是CSS 的属性,它有三个属性值:translate(位移) 、rotate(旋转)、scale(缩放) 。transform 对行内元素无效,对行内块元素和块元素才有效
1、转换之位移translate
- 转换不脱标,位移和相对定位有异曲同工之妙
- 写2个值,第1个值是x轴上位移,正值向右,负值向左;第2个值是y轴上移动,正值向下,负值向上
- 写1个值,代表x轴上位移
- 单独设置某个方向的移动距离:translateX()或translateY()
- 写百分比,位移的距离是自身的宽高的百分比。
灰色盒子向右位移 100px
<style>
.box1 {
transform: translate(100px);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
灰色盒子向右位移50px 再向下位移50px
<style>
.box1 {
transform: translate(50px,50px);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
灰色盒子向右位移100% ,再向下位移100%
<style>
.box1 {
transform: translate(100%,100%);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
灰色盒子向上位移50%
<style>
.box1 {
transform: translateY(-50%);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
2.转换之旋转 rotate(2D)
- 2d转换之旋转 正值顺时针,负值逆时针
红色盒子顺时针旋转 30度
<style>
.box {
transform: rotate(30deg);
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box"></div>
</body>
红色盒子 hover 的时候 逆时针位移 90度
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all 1s;
}
.box:hover{
transform: rotate(-90deg);
}
</style>
如何让一个盒子顺时针迅速旋转不停
<style>
.box {
margin: 30px auto;
width: 100px;
height: 100px;
background-color: red;
animation: translate 1s infinite linear;
}
@keyframes translate {
0%{
transform: rotate(0);
}
100%{
transform: rotate(360deg);
}
}
</style>
<body>
<div class="box"></div>
</body>
3、转换之缩放scale
灰色盒子缩小0.5倍
<style>
.box1 {
transform: scale(0.5);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
灰色盒子放大1.2倍
<style>
.box1 {
transform: scale(1.2);
width: 100px;
height: 100px;
background-color: #ccc;
}
.box2 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
灰色盒子 hover 的时候放大 1.5倍
<style>
.box {
width: 100px;
height: 100px;
background-color: #ccc;
transition: all 1s;
}
.box:hover {
transform: scale(1.5);
}
</style>
<body>
<div class="box"></div>
</body>
注意:转换复合属性可以连写,一定要注意位移写在旋转的前面,不然被层叠掉了
<style>
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all 3s;
}
.box:hover{
transform: translate(500px) rotate(360deg)
}
</style>
<body>
<div class="box"></div>
</body>