一个 transition 会在一段时间内平滑地将属性从旧值动画到新值,而不是立即改变它。你声明动画什么以及持续多长时间,然后通过改变属性(通常通过 :hover 或一个 class)来触发它。
css
{
: blue;
: background ease;
}
{
: darkblue;
}
transition: background 0.3s ease 0s;
/* │ │ │ └── delay before starting */
/* │ │ └─────── timing function (the easing curve) */
/* │ └──────────── duration */
/* └─────────────────────── property to animate (or `all`) */
.card {
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.card:hover {
transform: translateY(-4px); /* lifts up */
box-shadow: 0 8px 20px rgba(0,0,0,0.2); /* + deeper shadow */
}
列出每个属性(用逗号分隔),而不是使用 all,它可能会意外地动画你不想动画的东西,并损害性能。
transition-timing-function: ease; /* slow-fast-slow (default) */
/* linear | ease-in | ease-out | ease-in-out */
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); /* custom curve */
/* ✅ cheap — GPU-composited, no layout recalculation */
transition: transform 0.3s, opacity 0.3s;
/* ❌ expensive — animating width/top/left triggers layout on every frame */
transition: width 0.3s, left 0.3s;
优先动画 transform 和 opacity;它们由合成器处理,不需要重新运行 layout,所以它们保持流畅(60fps)。
@media (prefers-reduced-motion: reduce) {
* { transition: none; } /* respect users who get motion sickness */
}
Transition 添加了使 UI 感觉响应迅速和生动的精致感(hover 效果、平滑的状态变化),只需一行代码。
知道为了性能而动画 transform/opacity ——并尊重 prefers-reduced-motion —— 这就是将平滑、无障碍的动作与卡顿的动画区分开来的东西。