cubic-bezier()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

cubic-bezier() CSS 函数使用三次贝塞尔曲线创建平滑过渡。作为<easing-function>,它可用于平滑插值的开始和结束。

语法

css
cubic-bezier(0.25, 0.1, 0.25, 1)
cubic-bezier(0.1, -0.6, 0.2, 0)
cubic-bezier(0, 0, 1, 1)

参数

该函数接受以下四个参数,它们表示两个控制点的坐标:

<x1>

一个<number>,表示第一个控制点的 x 轴坐标。它必须在 [0, 1] 范围内。

<y1>

一个<number>,表示第一个控制点的 y 轴坐标。

<x2>

一个<number>,表示第二个控制点的 x 轴坐标。它必须在 [0, 1] 范围内。

<y2>

一个<number>,表示第二个控制点的 y 轴坐标。

描述

三次贝塞尔函数,通常称为“平滑”缓动函数,将输入进度与输出进度关联起来,两者都表示为<number>,其中 0.0 表示初始状态,1.0 表示最终状态。如果三次贝塞尔曲线无效,CSS 会忽略整个属性。

三次贝塞尔曲线由四个点定义:P0、P1、P2 和 P3。点 P0 和 P3 表示曲线的起点和终点。在 CSS 中,起点 P0 固定为 (0, 0),终点 P3 固定为 (1, 1),而中间点 P1 和 P2 分别由函数参数 (<x1>, <y1>)(<x2>, <y2>) 定义。x 轴表示输入进度,y 轴表示输出进度。

Graph of Input progress to Output progress showing an S-shaped line curving from the origin to (1, 1) with the Bezier control points P1(0.1, 0.6) and P2(0.7, 0.2).

并非所有三次贝塞尔曲线都适合作为缓动函数,因为并非所有曲线都是数学函数;即,对于给定的 x 轴坐标,其值为零或一的曲线。在 P0 和 P3 固定为 CSS 定义的情况下,当且仅当 P1 和 P2 的 x 轴坐标都在 [0, 1] 范围内时,三次贝塞尔曲线才是一个函数,因此有效。

当 P1 或 P2 的纵坐标超出 [0, 1] 范围时,三次贝塞尔曲线可能导致值超出最终状态然后返回。在动画中,这会产生一种“弹跳”效果。

Graphs of the easing function cubic-bezier(0.3, 0.2, 0.2, 1.4), one of which shows the output progress going above 1 starting from a certain input progress, the other shows the output progress reaching and then staying at 1.

然而,如果输出超出允许范围,某些属性会限制输出。例如,rgb() 中大于 255 或小于 0 的颜色分量将被剪裁到最接近的允许值(分别为 2550)。某些 cubic-bezier() 值就表现出这种特性。

正式语法

<cubic-bezier()> = 
cubic-bezier( [ <number [0,1]> , <number> ]#{2} )

示例

弹跳效果

在此示例中,红球从其原始位置过渡时会从盒子中弹跳出来。这是因为 P2 值之一 2.3 超出了 [0, 1] 范围。

css
span {
  transition: translate 0.3s cubic-bezier(0.3, 0.8, 0.3, 2.3);
}

使用 cubic-bezier() 函数

这些三次贝塞尔曲线在 CSS 中是有效的

css
/* The canonical Bézier curve with four <number> in the [0,1] range */
cubic-bezier(0.1, 0.7, 1.0, 0.1)

/* Using <integer> is valid because any <integer> is also a <number> */
cubic-bezier(0, 0, 1, 1)

/* Negative values for ordinates are valid, leading to bouncing effects */
cubic-bezier(0.1, -0.6, 0.2, 0)

/* Values greater than 1.0 for ordinates are also valid */
cubic-bezier(0, 1.1, 0.8, 4)

这些三次贝塞尔曲线定义是无效的

css
/* Parameters must be numbers */
cubic-bezier(0.1, red, 1.0, green)

/* X coordinates must be in the [0, 1] range */
cubic-bezier(2.45, 0.6, 4, 0.1)

/* There must be exactly four parameters */
cubic-bezier(0.3, 2.1)

/* X coordinates must be in the [0, 1] range */
cubic-bezier(-1.9, 0.3, -0.2, 2.1)

规范

规范
CSS 缓动函数级别 1
# 三次贝塞尔缓动函数

浏览器兼容性

另见