CSS transition通过指定属性、持续时间、速度曲线和延迟实现平滑动画,如按钮悬停变色;可同时过渡多个属性或使用all简写,但仅支持有数值的属性,需注意auto、display等限制及性能影响。

CSS transition 是实现元素平滑动画效果的简单方式,适用于颜色、大小、位置等属性的变化。它不会创建复杂的动画序列,但能让交互更自然,比如鼠标悬停时按钮变色、菜单展开收缩等。
1. 基本语法与常用属性
要使用 transition,需定义以下四个关键属性:
- transition-property:指定要过渡的 CSS 属性,如 width、background-color
- transition-duration:过渡持续时间,单位为秒(s)或毫秒(ms)
- transition-timing-function:控制动画的速度曲线,如 ease、linear、ease-in-out
- transition-delay:延迟多久开始动画
也可以用简写形式一次性设置:
transition: property duration timing-function delay;2. 实现一个简单的悬停动画
以按钮背景色变化为例,当鼠标悬停时颜色渐变:
立即学习“前端免费学习笔记(深入)”;
.btn {
background-color: #007bff;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #0056b3;
}
这里只对 background-color 做过渡,持续 0.3 秒,使用缓动效果,视觉上更自然。
3. 同时过渡多个属性
如果需要同时改变多个样式,可以这样写:
.box {
width: 100px;
height: 100px;
background: red;
transition: width 0.4s ease, height 0.4s ease, transform 0.4s ease;
}
.box:hover {
width: 150px;
height: 150px;
transform: rotate(15deg);
}
也可以直接用 all 表示所有可动画属性:
transition: all 0.4s ease;4. 注意事项与常见问题
使用 transition 时要注意几点:
- 只有有明确数值的属性才能过渡,比如 display: none 到 block 无法渐变
- 某些属性如 height: auto 不支持过渡,建议用 max-height 替代
- 过渡只在属性发生变化时触发,可通过 JS 修改 class 或内联样式来启动
- 移动端注意性能,避免对过多属性或高频率操作使用长过渡










