css动画怎么制作
CSS动画制作方法
CSS动画主要通过@keyframes规则和animation属性实现,以下是具体实现方式:
定义关键帧动画
使用@keyframes定义动画序列,从0%到100%描述动画各阶段样式变化:
@keyframes slidein {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(0);
}
}
应用动画到元素
通过animation属性将动画绑定到元素:
.element {
animation: slidein 3s ease-in-out infinite;
}
常用动画属性
animation-name
指定使用的@keyframes名称:
animation-name: slidein;
animation-duration 设置动画周期时长(单位秒/毫秒):
animation-duration: 2s;
animation-timing-function 定义速度曲线:

animation-timing-function: ease|linear|ease-in|ease-out|ease-in-out|cubic-bezier();
animation-delay 设置动画延迟启动时间:
animation-delay: 0.5s;
animation-iteration-count 定义播放次数(数字或infinite):
animation-iteration-count: infinite;
animation-direction 控制是否交替反向播放:
animation-direction: normal|reverse|alternate|alternate-reverse;
animation-fill-mode 设置动画前后如何应用样式:

animation-fill-mode: none|forwards|backwards|both;
复合写法示例
.box {
animation: pulse 1.5s ease-in-out 0.5s infinite alternate;
}
实际应用案例
淡入效果
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in {
animation: fadeIn 1s forwards;
}
弹跳效果
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
.bounce {
animation: bounce 0.8s infinite;
}
旋转加载动画
@keyframes spin {
to { transform: rotate(360deg); }
}
.spinner {
animation: spin 1s linear infinite;
border: 4px solid rgba(0,0,0,0.1);
border-radius: 50%;
border-top-color: #09f;
}
性能优化建议
使用transform和opacity属性制作动画,这些属性不会触发重排
避免在动画中使用width、height、margin等会引发布局变化的属性
对需要动画的元素添加will-change属性提前告知浏览器:
.animated-element {
will-change: transform, opacity;
}






