Skip to content

CSS3 过渡

CSS 过渡(transitions)提供了一种控制 CSS 属性从一个值平滑地变化到另一个值的方式。变化不再是瞬间发生,而是通过过渡在指定的时长内平滑地完成。

这通常用于创建悬停(hover)效果、响应用户交互的 UI 元素动画,或平滑地改变状态。

CSS 过渡及其相关属性在所有现代 Web 浏览器中都得到了广泛支持。通常不再需要供应商前缀(vendor prefixes)。

要创建一个过渡效果,你需要在想要应用动画的元素上定义两件事:

  1. 哪些 CSS 属性应该进行过渡: 使用 transition-property 指定。
  2. 过渡应该花费多长时间: 使用 transition-duration 指定。

当指定的 CSS 属性值发生变化时(例如,由于 :hover 状态、通过 JavaScript 添加类等),过渡效果会自动开始。

示例:在 0.5 秒内过渡 background-color:

.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
/* 定义过渡 */
transition-property: background-color;
transition-duration: 0.5s;
/* 可选:添加时间函数 */
transition-timing-function: ease-out;
}
/* 定义触发过渡的状态变化 */
.button:hover {
background-color: darkblue;
}

当用户将鼠标悬停在按钮上时,background-color 从 blue 变为 darkblue。由于为 background-color 定义了过渡,这种变化会在 0.5 秒内逐渐发生,而不是瞬间变化。

注意:如果未指定 transition-duration 或将其设置为 0s(默认值),变化将是瞬时的,并且不会看到过渡效果。

有几个属性控制过渡的行为:

  • transition-property: 指定应应用过渡的 CSS 属性名称。你可以用逗号分隔列出多个属性(例如,width, background-color, transform),或使用特殊值 all 来过渡任何可动画化且发生变化的属性。

  • transition-duration: 定义过渡完成所需的时间(例如,2s,300ms)。如果过渡多个属性,可以为不同的属性指定不同的时长。

  • transition-timing-function: 控制过渡的加速度曲线(中间值如何计算)。常见值包括 ease(默认)、linear、ease-in、ease-out、ease-in-out、steps() 和 cubic-bezier(...) 用于自定义曲线。

  • transition-delay: 指定在属性变化触发后,实际开始过渡前的等待时间(例如,1s)。

示例:过渡多个属性,具有不同的时长和延迟:

.box {
width: 100px;
height: 100px;
background-color: lightcoral;
opacity: 0.5;
transition-property: width, background-color, opacity;
transition-duration: 2s, 1s, 0.5s; /* width: 2s, background: 1s, opacity: 0.5s */
transition-timing-function: ease-in-out;
transition-delay: 0.5s; /* Wait 0.5s before starting all transitions */
}
.box:hover {
width: 200px;
background-color: darkred;
opacity: 1;
}

通常使用 transition 简写属性将 transition-property、transition-duration、transition-timing-function 和 transition-delay 设置在一个声明中。

顺序很重要,尤其用于区分时长和延迟(第一个时间值是时长,第二个是延迟)。

使用简写属性的示例:

.button {
background-color: green;
transform: scale(1);
/* 简写: property duration timing-function delay */
transition: background-color 0.4s ease-out, transform 0.3s ease;
}
.button:hover {
background-color: darkgreen;
transform: scale(1.1);
}

使用 all 作为属性:

.element {
/* 在 0.3 秒内过渡所有可动画属性 */
transition: all 0.3s ease-in-out;
}

并非所有 CSS 属性都可以平滑过渡。通常,接受数值(如 width、height、opacity、font-size)、颜色值或可以插值的特定关键字(如 visibility、transforms)的属性是可动画的。

像 font-family 或 display(通常)这样的属性无法在不同值之间平滑过渡。

为了更平滑、性能更好的过渡(尤其是在性能较弱的设备上),优先过渡 transform(例如,translate、scale、rotate)和 opacity。这些属性通常可以由浏览器的合成器线程处理,避免了昂贵的布局重新计算或重绘。

过渡 width、height、margin、padding 或 top/left 等属性有时会触发布局变化,这可能会降低性能。

属性描述
transition设置以下四个过渡属性的简写属性。
transition-property指定应用过渡的 CSS 属性。
transition-duration指定过渡发生的时间长度。
transition-timing-function指定过渡的速度曲线(加速度)。
transition-delay指定过渡开始前的延迟时间。