CSS @keyframes 简明指南
本文内容基于 AI 生成结果整理,可能包含不准确信息,仅供参考使用。
此演示仅在桌面端浏览器中可用
基本概念
@keyframes 用于创建 CSS 动画,通过定义动画序列中的关键帧来控制元素的变化过程。
基础语法
css
@keyframes 动画名称 {
0% {
/* 起始状态 */
}
50% {
/* 中间状态 */
}
100% {
/* 结束状态 */
}
}
应用动画
css
.element {
animation: 动画名称 持续时间 时间函数 延迟 重复次数 方向;
}
动画属性详解
animation-name
: 指定@keyframes
动画名称animation-duration
: 动画持续时间(如 2s)- animation-timing-function : 速度曲线(ease, linear, ease-in-out 等)
animation-delay
: 动画开始前的延迟animation-iteration-count
: 重复次数(数字或 infinite)animation-direction
: 方向(normal, reverse, alternate, alternate-reverse)animation-fill-mode
: 动画执行前后如何应用样式(none, forwards, backwards, both)animation-play-state
: 控制动画运行或暂停(running, paused)
注意事项
- 不是所有 CSS 属性都可以动画化,如
display
属性。 - 使用
transform
和opacity
动画性能较好。 - 复杂的动画可能会影响页面性能,特别是在移动设备上。
- 考虑添加
@media (prefers-reduced-motion: reduce)
为对运动敏感的用户提供替代方案。
实用动画示例
淡入淡出效果
css
@keyframes fade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.fade {
animation: fade 2s infinite alternate;
}
左右摇摆效果
css
@keyframes swing {
0%,
100% {
transform: translateX(0);
}
25% {
transform: translateX(30px);
}
75% {
transform: translateX(-30px);
}
}
.swing {
animation: swing 3s infinite ease-in-out;
}
脉冲放大效果
css
@keyframes pulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
}
.pulse {
animation: pulse 2s infinite;
}
连续旋转效果
css
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.rotate {
animation: rotate 4s infinite linear;
}
组合动画效果
css
@keyframes complex {
0% {
transform: translateY(0) rotate(0deg);
background: blue;
}
50% {
transform: translateY(-50px) rotate(180deg);
background: red;
}
100% {
transform: translateY(0) rotate(360deg);
background: blue;
}
}
.complex {
animation: complex 6s infinite ease-in-out;
}
颜色渐变效果
css
@keyframes color-change {
0% {
color: red;
}
33% {
color: yellow;
}
66% {
color: green;
}
100% {
color: blue;
}
}
.color-change {
animation: color-change 8s infinite;
}