Transform 属性允许你对元素进行旋转、缩放、移动或倾斜。
translateX(x)
- 水平移动translateY(y)
- 垂直移动translateZ(z)
- Z轴移动(3D空间)rotate(deg)
- 旋转元素scale(x)
- 缩放元素rotate(45deg) translateX(20px)
.box {
transform: rotateY(50deg) translateZ(0px);
transition: transform 0.5s ease-out;
}
.card {
transform: rotateY(50deg) translateZ(100px);
transform-style: preserve-3d;
perspective: 1000px;
transition: transform 0.8s cubic-bezier(0.25, 0.8, 0.25, 1);
}
Transition 提供元素从一种样式逐渐变为另一种样式的效果。
.transition-demo {
width: 180px;
transition: width 1.5s ease-in-out,
background-color 1s ease-in-out;
}
.transition-demo:hover {
width: 350px;
background-color: #d9534f;
}
transition-property
- 指定要过渡的CSS属性transition-duration
- 过渡持续时间transition-timing-function
- 速度曲线transition-delay
- 过渡延迟时间transition: width 2s ease-in-out 0.5s,
height 3s linear 0.2s,
opacity 1s ease-out;
使用 @keyframes
规则创建动画。
animation-name
- 指定@keyframes动画名称animation-duration
- 动画持续时间animation-delay
- 动画延迟时间animation-iteration-count
- 播放次数(infinite表示无限)animation-timing-function
- 速度曲线animation-fill-mode
- 动画前后如何应用样式animation-direction
- 动画播放方向1. 从...到...:
@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
2. 百分比关键帧:
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
25% {
transform: translateY(-20px);
}
50% {
transform: translateY(0);
}
75% {
transform: translateY(-10px);
}
}
Animate.css 是一个现成的CSS动画库,提供多种预设动画效果。
animate__animated
animate__bounce
animate__infinite
实现无限循环<!-- 引入Animate.css -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<!-- 使用动画 -->
<div class="animate__animated animate__bounce animate__infinite">
弹跳效果
</div>
animate__bounce // 弹跳
animate__fadeIn // 淡入
animate__fadeOut // 淡出
animate__flip // 翻转
animate__pulse // 脉冲
animate__rotateIn // 旋转进入
animate__shakeX // 水平摇晃
animate__zoomIn // 缩放进入
transform
和opacity
属性创建动画性能最佳width
, height
, margin
等will-change: transform, opacity;
提前告知浏览器哪些属性会变化requestAnimationFrame
替代setTimeout
/setInterval