css动画制作
CSS动画基础语法
CSS动画通过@keyframes规则定义动画序列,结合animation属性实现。基本结构分为两部分:关键帧定义和元素动画绑定。
/* 关键帧定义 */
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
/* 元素应用动画 */
.element {
animation: slideIn 1s ease-out forwards;
}
关键属性详解
animation复合属性
包含以下子属性(空格分隔):

animation-name: 指定@keyframes名称animation-duration: 动画持续时间(如2s)animation-timing-function: 速度曲线(ease/linear/cubic-bezier())animation-delay: 延迟启动时间animation-iteration-count: 重复次数(infinite表示无限循环)animation-direction: 播放方向(normal/reverse/alternate)animation-fill-mode: 结束状态保持(forwards保留最后一帧)
关键帧控制
关键帧支持百分比定义多阶段动画:
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.2); }
100% { transform: scale(1); }
}
性能优化技巧
- 优先使用
transform和opacity属性(GPU加速) - 避免频繁触发重排的属性如
width/height - 使用
will-change: transform预声明变化 - 减少动画元素数量(尤其移动端)
实用动画示例
悬停放大效果

.button {
transition: transform 0.3s ease;
}
.button:hover {
transform: scale(1.05);
}
无限旋转动画
@keyframes spin {
to { transform: rotate(360deg); }
}
.loader {
animation: spin 2s linear infinite;
}
浏览器兼容方案
通过前缀确保兼容性:
@-webkit-keyframes example { /* Safari/Chrome */ }
@-moz-keyframes example { /* Firefox */ }
.element {
-webkit-animation: example 1s;
-moz-animation: example 1s;
}





