CSS的transition属性通过设置property、duration、timing-function和delay实现元素状态变化的平滑动画,如:hover时颜色渐变或尺寸缩放;可单独指定属性或使用all对多个属性应用过渡,并配合ease、linear等速度曲线控制动画节奏,提升交互体验。

CSS 的 transition 属性可以让元素在状态变化时实现平滑的动画效果,比如鼠标悬停时颜色渐变、按钮缩放等。它适合做简单的交互动画,不需要关键帧(keyframes),使用起来非常直观。
1. 基本语法和属性
transition 是一个复合属性,可以设置以下子属性:
- property:要过渡的 CSS 属性,如 width、color、opacity 等,用 all 表示所有可动画属性
- duration:过渡持续时间,单位是秒(s)或毫秒(ms)
- timing-function:过渡的速度曲线,如 ease、linear、ease-in-out
- delay:延迟多久开始动画
写法示例:
pre { transition: property duration timing-function delay; }例如:
立即学习“前端免费学习笔记(深入)”;
pre { transition: background-color 0.3s ease 0.1s; }2. 实现鼠标悬停动画
常见的用途是配合 :hover 实现视觉反馈。比如让按钮背景色缓慢变化:
pre { .button { background-color: #007bff; color: white; padding: 10px 20px; border: none; transition: background-color 0.4s ease; } .button:hover { background-color: #0056b3; } }当鼠标移到按钮上时,背景色会在 0.4 秒内平滑变深。
3. 多属性动画与 all 的使用
如果想让多个属性都有过渡效果,可以分别列出,或使用 all:
pre { .box { width: 100px; height: 100px; background: red; transition: all 0.5s ease; } .box:hover { width: 150px; height: 150px; background: blue; transform: rotate(15deg); } }这里宽度、高度、背景色和旋转都会产生过渡动画。
4. 常用 timing-function 选项
控制动画节奏很重要。常用值有:
- ease:慢开始,快中间,慢结束(默认)
- linear:匀速进行
- ease-in:慢开始
- ease-out:慢结束
- ease-in-out:两端慢,中间快
例如让动画更自然:
pre { transition: transform 0.3s ease-in-out; }基本上就这些。transition 不复杂但容易忽略细节,比如没设 duration 就不会动,或者属性不支持动画。掌握它能快速提升页面交互质感。










