CSS 动画与过渡效果完全指南:从过渡到关键帧动画
Introduction
CSS 动画能力分为两大类:transition(过渡)用于简单的状态变化动画,@keyframes(关键帧动画)用于复杂的多步骤、循环、主动画效果。两者结合可以满足绝大多数 UI 交互动画需求,无需引入 JavaScript 动画库。本文讲解两者的语法、性能优化及实战技巧。
transition 过渡
/* 完整语法:property duration timing-function delay */
.button {
background-color: #8b4513;
transition: background-color 0.3s ease-in-out, transform 0.2s ease;
}
.button:hover {
background-color: #c0392b;
transform: scale(1.05);
}
/* 分开写更容易阅读 */
.box {
transition-property: all; /* 要过渡的属性 */
transition-duration: 0.3s; /* 持续时间 */
transition-timing-function: ease-in-out; /* 缓动函数 */
transition-delay: 0s; /* 延迟 */
}
/* 常用缓动函数 */
ease /* 缓入缓出,默认值 */
linear /* 匀速 */
ease-in /* 缓入(慢→快)*/
ease-out /* 缓出(快→慢)*/
cubic-bezier(0.68, -0.55, 0.265, 1.55) /* 自定义贝塞尔曲线 */
@keyframes 关键帧动画
/* 定义动画 */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 百分比写法(多步骤)*/
@keyframes heartbeat {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.2); }
}
/* 使用动画 */
.element {
animation: fadeIn 0.5s ease-in-out forwards;
/* animation-name / duration / timing-function / delay / fill-mode */
}
/* forwards 填充模式:让动画停在最后一帧 */
实战:常见动画效果
/* 1. 渐入效果 */
.fade-in {
animation: fadeIn 0.5s ease-out forwards;
opacity: 0; /* 必须初始为透明,否则看不到效果 */
}
/* 2. 加载动画(三个跳动点)*/
.loading-dot {
animation: bounce 1.4s infinite ease-in-out both;
}
.loading-dot:nth-child(1) { animation-delay: -0.32s; }
.loading-dot:nth-child(2) { animation-delay: -0.16s; }
.loading-dot:nth-child(3) { animation-delay: 0s; }
@keyframes bounce {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}
/* 3. 滑入侧边栏 */
.sidebar {
transform: translateX(-100%);
transition: transform 0.3s ease-out;
}
.sidebar.open { transform: translateX(0); }
性能优化:transform 与 opacity
/* 高性能动画(触发 GPU 加速)*/
/* 浏览器会为 transform 和 opacity 创建独立的图层(layer),
动画过程中不会触发重排(reflow)和重绘(repaint)*/
.good-animation {
transform: translateX(100px) scale(1.1); /* GPU 加速 */
opacity: 0.5; /* GPU 加速 */
}
/* 低性能动画(避免)*/
.bad-animation {
width: 100px; /* 触发布局重排 */
height: 100px; /* 触发布局重排 */
background-color: red; /* 触发重绘 */
font-size: 16px; /* 触发布局重排 */
}
/* 强制 GPU 加速(慎用,会增加内存占用)*/
.will-change-transform {
will-change: transform; /* 提前告知浏览器此元素将变化 */
}
运行效果
在浏览器中打开动画示例:按钮 hover 时颜色平滑渐变、鼠标移开时恢复;加载页面的三个点以心跳节奏循环跳动;侧边栏滑入/滑出时平滑流畅。开发者工具中 Performance 面板可观察动画是否触发了 layout 或 paint 阶段。
常见问题
- 动画不生效:检查元素初始状态是否设置了导致动画看不到的属性(如 opacity: 1 而动画是 0→1)。
- animation-fill-mode:forwards 让元素停在最后一帧,backwards 让元素在动画开始前显示第一帧,both 两者兼具。
- will-change 滥用:不要在大量元素上同时设置 will-change,会导致内存暴涨。
- animation 与 transition 同时用:两者可以叠加,但要注意同时使用可能导致意外效果。建议明确分开:状态切换用 transition,主动画用 animation。
- MDN CSS 动画指南:MDN CSS Animations
- CSS 动画性能:Google Web Fundamentals
- 缓动函数库:easings.net