CSS `cubic-bezier()` Function: Creating Custom Animation Timing
Master smooth and customized animations in CSS using the `cubic-bezier()` function. This tutorial explains cubic Bezier curves, demonstrates how to define custom animation timings using control points, and provides examples for creating unique and engaging animation effects.
Understanding the CSS `cubic-bezier()` Function
Cubic Bezier Curves and Smooth Transitions
The CSS cubic-bezier()
function is a timing function that defines a cubic Bezier curve. Bezier curves are mathematically defined curves used to create smooth transitions in animations and transitions. They're commonly used in graphic design software (like Inkscape or Adobe Illustrator) and are now available in CSS for creating customized animation effects.
Bezier Curve Points
A cubic Bezier curve is defined by four points: P0, P1, P2, and P3. P0 and P3 are the start and end points (called *anchors*), and P1 and P2 are control points (called *handles*) that influence the curve's shape. In CSS, P0 is always (0,0) representing the start of the animation, and P3 is always (1,1) representing the end of the animation. The x and y coordinates of the control points P1 and P2 (passed to `cubic-bezier()`) must be between 0 and 1.
`cubic-bezier()` Syntax
The syntax for the cubic-bezier()
function is:
cubic-bezier(x1, y1, x2, y2)
Where:
x1
andx2
are the x-coordinates of the control points (between 0 and 1).y1
andy2
are the y-coordinates of the control points (between 0 and 1).
If you provide invalid values (outside the 0-1 range), the function defaults to a linear transition (cubic-bezier(0, 0, 1, 1)
).
Example: Using `cubic-bezier()` with Transitions
The cubic-bezier()
function can be used with the `transition-timing-function` or `animation-timing-function` properties to create custom animation speeds. This allows you to fine-tune the pacing of your animations for smoother and more visually appealing results.
Example (Using `transition-timing-function`)
div {
transition-property: width;
transition-duration: 2s;
transition-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1); /* Example curve */
}
div:hover {
width: 200px;
}
This example creates a smooth transition for the width of the div element when the mouse hovers over it. The specified `cubic-bezier()` values define the curve of the transition.