CSS 过渡效果(CSS Transitions)允许你在元素的状态发生变化时,平滑地改变其属性值。通过定义过渡效果,你可以控制属性值的变化速度、延迟、持续时间等,从而实现更加动态和流畅的视觉效果。
1. transition
transition
是一个简写属性,用于同时设置 transition-property
、transition-duration
、transition-timing-function
和 transition-delay
。
语法:
transition: property duration timing-function delay;
示例:
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s ease-in-out 1s;
}
div:hover {
width: 200px;
}
在这个例子中,当鼠标悬停在 div
元素上时,宽度会在 1 秒延迟后,以 ease-in-out
的方式在 2 秒内从 100px 过渡到 200px。

2. transition-delay
transition-delay
属性定义了过渡效果开始之前的延迟时间。
语法:
transition-delay: time;
示例:
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s;
transition-delay: 1s;
}
div:hover {
width: 200px;
}
在这个例子中,当鼠标悬停在 div
元素上时,宽度变化会在 1 秒延迟后开始。
3. transition-duration
transition-duration
属性定义了过渡效果的持续时间。
语法:
transition-duration: time;
示例:
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s;
}
div:hover {
width: 200px;
}
在这个例子中,当鼠标悬停在 div
元素上时,宽度变化会在 2 秒内完成。
4. transition-property
transition-property
属性指定了哪些 CSS 属性会应用过渡效果。
语法:
transition-property: property;
示例:
div {
width: 100px;
height: 100px;
background-color: red;
transition-property: width;
transition-duration: 2s;
}
div:hover {
width: 200px;
}
在这个例子中,只有 width
属性会应用过渡效果。
5. transition-timing-function
transition-timing-function
属性定义了过渡效果的速度曲线。
语法:
transition-timing-function: timing-function;
常用值:
linear
: 匀速过渡。ease
: 默认值,慢速开始,然后加速,最后减速。ease-in
: 慢速开始。ease-out
: 慢速结束。ease-in-out
: 慢速开始和结束。cubic-bezier(n,n,n,n)
: 自定义贝塞尔曲线。
示例:
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s ease-in-out;
}
div:hover {
width: 200px;
}
在这个例子中,当鼠标悬停在 div
元素上时,宽度变化会以 ease-in-out
的速度曲线进行。
6.支持过渡的属性 transition-property
尺寸相关:
width,height,max-width,max-height,min-width,min-height
位置相关:
top,bottom,left,right
颜色相关:
color,background-color,border-color,outline-color
透明度:
opacity
变换相关:
transform(如旋转、缩放、平移等),transform-origin
字体相关:
font-size,font-weight
边框相关:
border-width,border-radius
阴影相关:
box-shadow,text-shadow
布局相关:
margin,padding,gap
其他:
z-index,visibility(虽然 visibility 本身不可过渡,但可以与 opacity 结合使用)