css3 动画制作
CSS3 动画制作基础
CSS3 动画通过 @keyframes 规则和 animation 属性实现。定义关键帧后,将其绑定到元素上,设置持续时间、延迟、循环方式等参数。
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
.element {
animation: slideIn 1s ease-in-out;
}
关键帧定义
使用 @keyframes 定义动画序列,from 和 to 分别表示起始和结束状态,也可用百分比指定中间步骤。
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
动画属性
animation 是以下子属性的简写:
animation-name: 关键帧名称animation-duration: 动画时长(如2s)animation-timing-function: 速度曲线(如ease,linear)animation-delay: 延迟启动时间animation-iteration-count: 循环次数(infinite表示无限)animation-direction: 播放方向(alternate来回播放)animation-fill-mode: 结束后的样式保留(如forwards)
.box {
animation: pulse 2s ease-in-out 0.5s infinite alternate;
}
变换与过渡
结合 transform 实现位移、旋转、缩放等效果,transition 用于属性变化的平滑过渡。
.button {
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #ff0000;
transform: scale(1.1);
}
性能优化
- 优先使用
opacity和transform,它们可通过 GPU 加速。 - 避免频繁触发重排(如修改
width/height)。 - 使用
will-change提示浏览器优化。
.optimized {
will-change: transform;
}
实际案例:旋转加载动画
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.loader {
animation: spin 1s linear infinite;
border: 4px solid rgba(0,0,0,0.1);
border-radius: 50%;
border-top-color: #3498db;
width: 40px;
height: 40px;
}






