transition可实现CSS样式平滑过渡,通过property、duration、timing-function和delay四个子属性控制动画效果,常用于鼠标悬停等交互场景。

在CSS中,transition 可以让元素从一种样式平滑地过渡到另一种样式,实现渐变动画效果。它常用于鼠标悬停、状态变化等交互场景。
1. 基本语法
使用 transition 属性需要定义以下四个子属性(可简写):
- property:指定要过渡的CSS属性,如 width、color、opacity 等
- duration:过渡持续时间,单位为秒(s)或毫秒(ms)
- timing-function:过渡的速度曲线,如 ease、linear、ease-in-out
- delay:延迟多久开始过渡
示例:
pre {transition: property duration timing-function delay;
}
2. 实现颜色渐变效果
比如让一个按钮的背景色在鼠标悬停时缓慢变为红色:
立即学习“前端免费学习笔记(深入)”;
.button {background-color: blue;
transition: background-color 0.5s ease;
}
.button:hover {
background-color: red;
}
这样,背景色会在0.5秒内从蓝色渐变到红色,使用 ease 缓动函数更自然。
3. 多属性过渡
如果想同时过渡多个属性,可以用逗号分隔:
.box {width: 100px;
height: 100px;
background-color: green;
transition: width 0.4s ease, height 0.4s ease, background-color 0.6s linear;
}
.box:hover {
width: 150px;
height: 150px;
background-color: yellow;
}
宽度和高度变化较快,背景色变化稍慢且匀速。
4. 常见可过渡属性
以下属性支持 transition 动画:
- 颜色类:color、background-color、border-color
- 尺寸类:width、height、font-size
- 位置类:margin、padding、top、left、transform
- 透明度:opacity
- 变换:transform(rotate、scale、translate)
注意:display 和 z-index 等非数值属性不能直接过渡。
基本上就这些,合理使用 transition 能让界面更生动自然。










