动画性能优化
约 379 字大约 1 分钟
布欧-Lewyon
2026-05-16
GPU 加速
浏览器将页面绘制分为三个层次:
仅 transform 和 opacity 的动画触发合成(Composite)阶段,不触发 Layout/Paint,性能最佳。
/* ❌ 低性能——触发 Layout */
.element { animation: move 1s; }
@keyframes move {
from { left: 0; }
to { left: 100px; }
}
/* ✅ 高性能——仅 Composite */
.element { animation: move 1s; }
@keyframes move {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}will-change
提前告知浏览器哪些属性会变化,以便优化:
.element {
will-change: transform, opacity;
/* 仅对即将动画的元素使用,用完移除 */
}⚠️ 不要滥用:过度使用会消耗大量内存。只在确定需要动画时使用,动画结束后移除或通过 JS 控制。
contain
contain 将元素从页面布局中隔离:
.card {
contain: content; /* 隔离布局、样式、绘制 */
/* 子元素的变化不影响外部,浏览器可独立优化 */
}性能对照表
| 变换方式 | 触发阶段 | 性能 |
|---|---|---|
transform | Composite | ✅ 最佳 |
opacity | Composite | ✅ 最佳 |
top / left | Layout + Paint + Composite | ❌ 差 |
width / height | Layout + Paint + Composite | ❌ 差 |
background | Paint + Composite | ⚠️ 一般 |
小结
| 优化技巧 | 说明 |
|---|---|
使用 transform 替代 top/left | 避免 Layout 重排 |
使用 opacity 替代 visibility | 触发 Composite |
will-change | 提前告知浏览器 |
contain | 隔离元素渲染 |
@media (prefers-reduced-motion) | 尊重用户无动画偏好 |
上一节:关键帧 Animation 下一节:媒体查询与断点
