Animation API#
Creating animations in CSS mainly relies on the following key APIs:
-
@keyframesrule- Used to define the intermediate steps (keyframes) of an animation. In the
@keyframesrule, you can set the styles of an element at certain moments during the animation.
@keyframes example { from {background-color: red;} to {background-color: yellow;} }Or use percentages to specify multiple keyframes:
@keyframes example { 0% {background-color: red;} 50% {background-color: blue;} 100% {background-color: yellow;} }When does the
@keyframesrule trigger?- When an element is bound to the
animation-nameproperty, the keyframes defined in the@keyframesrule will be executed according to the specified timing and speed curve when the animation starts. - For example, the above
exampleanimation will be executed according to the settings of theanimation-durationandanimation-timing-functionproperties after being bound to an element in theanimation-nameproperty.
- Used to define the intermediate steps (keyframes) of an animation. In the
-
animation-nameproperty- Specifies the
@keyframesname that needs to be bound to the selector.
.element { animation-name: example; } - Specifies the
-
animation-durationproperty- Defines the time it takes to complete one cycle of the animation, such as seconds or milliseconds.
.element { animation-duration: 2s; } -
animation-timing-functionproperty- Defines the speed curve of the animation, such as
linear,ease,ease-in,ease-out,ease-in-out, orcubic-bezierfunctions.
.element { animation-timing-function: ease-in-out; }In CSS animations, you can control the speed of the animation by specifying the speed curve. Here are some commonly used speed curves:
-
linear- The speed of the animation is the same from start to finish. This means the animation proceeds smoothly at a constant speed, without acceleration or deceleration.
-
ease- The default speed curve. The animation starts slowly, accelerates, and then decelerates at the end. This makes the animation appear more natural, as it simulates the motion of objects in the real world.
-
ease-in- The animation starts slowly, and the speed gradually increases until the end. This curve is suitable for scenes that need to emphasize the beginning of the action.
-
ease-out- The animation starts at full speed and then gradually slows down until it stops. This curve is suitable for scenes that need to emphasize the end of the action.
-
ease-in-out- The animation starts and ends slowly, with the middle part moving at a faster speed. This speed curve is a combination of
ease-inandease-out, suitable for scenes that require a smooth transition.
- The animation starts and ends slowly, with the middle part moving at a faster speed. This speed curve is a combination of
-
cubic-bezier(n,n,n,n)- Allows you to customize a speed curve. The
cubic-bezierfunction accepts four parameters that define a cubic Bezier curve, allowing precise control over the acceleration and deceleration of the animation. CSS provides acubic-beziertool to help you visualize and adjust these four parameters.
ease-n. easy; comfortable, at ease
v. alleviate, ease, relax; move slowly; make easy; reduce; resign; familiarize
- Allows you to customize a speed curve. The
- Defines the speed curve of the animation, such as
-
animation-delayproperty- Sets the delay time before the animation starts.
.element { animation-delay: 1s; } -
animation-iteration-countproperty- Defines how many times the animation should play, which can be a number or
infiniteto indicate infinite repetition.
.element { animation-iteration-count: infinite; } - Defines how many times the animation should play, which can be a number or
-
animation-directionproperty- Specifies whether the animation should play in reverse on alternate cycles. Common values include
normal,reverse,alternate,alternate-reverse.
.element { animation-direction: alternate; } - Specifies whether the animation should play in reverse on alternate cycles. Common values include
-
animation-fill-modeproperty- Specifies how styles should be applied to the target element before and after the animation executes. For example,
forwardsretains the styles of the last keyframe.
.element { animation-fill-mode: forwards; }The
animation-fill-modeproperty in CSS animations is used to specify how an animation applies styles to its target element before and after execution. In short, it determines the style representation of the element before and after the animation executes. Theanimation-fill-modeproperty accepts the following values:none- The default value. Does not change the default behavior. The animation will not apply any styles to the target element, and the element will return to its state before the animation after it ends.
forwards- After the animation completes, the element will retain the styles determined by the last keyframe of the animation. That is, the element will keep the styles it had at the end of the animation.
backwards- The animation will immediately apply the styles of the first keyframe at the moment it is applied to the element, even if the animation is delayed. This means the element will immediately take on the styles of the animation's initial state until the animation actually begins.
both- The animation follows the rules of
forwardsandbackwards, meaning the animation will apply the styles of the first keyframe during the delay period and retain the styles of the last keyframe after the animation ends.
- The animation follows the rules of
For example, if you have a fade-out animation, you might want the element to remain transparent after the animation ends.
- Specifies how styles should be applied to the target element before and after the animation executes. For example,
-
animationshorthand property- You can use the
animationshorthand property to set all animation properties at once.
.element { animation: example 2s infinite ease-in-out; } - You can use the
-
animation-play-stateproperty- Controls the playback state of the animation. It can be set to
pausedto pause the animation orrunningto continue playing the animation.
.element { animation-play-state: paused; } - Controls the playback state of the animation. It can be set to
-
Using CSS variables to control animations
- CSS variables (custom properties) can be used in conjunction with animations to provide dynamic values or achieve theme customization.
:root { --animation-duration: 2s; } .element { animation-duration: var(--animation-duration); } -
Using
@mediaqueries and animations- You can combine media queries to apply different animation effects, making the animations responsive to different screen sizes or device characteristics.
@media (max-width: 600px) { .element { animation-name: exampleSmallScreen; } } -
will-changeproperty- Informs the browser in advance about the changes an element will undergo to optimize performance. While it does not directly control animation, appropriate use can enhance the smoothness of animations.
.element { will-change: transform, opacity; } -
Using CSS animations for performance optimization
- Whenever possible, use transform and opacity animations, as they can be hardware accelerated, improving animation performance.
-
Animation events
- Although CSS itself does not directly provide an event listening mechanism, in JavaScript, you can listen for animation-related events such as
animationstart,animationend, andanimationiterationto execute scripts at different stages of the animation.
document.querySelector('.element').addEventListener('animationend', function() { console.log('Animation ended'); }); - Although CSS itself does not directly provide an event listening mechanism, in JavaScript, you can listen for animation-related events such as
Practical Animation API#
1. Using keyframes#
.button {
cursor: pointer;
animation-duration: 3ms;
}
@keyframes button {
0% {
background-color: aqua;
}
100% {
background-color: bisque;
}
}
Question: It cannot be triggered, when does the animation generally trigger?
.button {
cursor: pointer;
animation-duration: 3s;
animation-name: bgcolor;
animation-delay: 0s;
animation-timing-function: ease-in;
background-color: aqua;
animation-fill-mode: both;
animation-iteration-count: infinite;
}
@keyframes bgcolor {
0% {
background-color: rgb(0, 140, 140);
}
100% {
background-color: rgb(208, 127, 29);
}
}
- The
animation-nameproperty assigns the name of the keyframes to it, allowing the animation to be triggered. It will trigger once by default when loaded for the first time if you bind it. - The
animation-durationproperty indicates the duration of the animation; - The
animation-delayproperty indicates the delay time of the animation; - The
animation-timing-functionis the animation timing function, which indicates how the animation executes; linear, ease, ease-in, ease-in-out, etc. And ease means easy, alleviate, ease-in means gradually entering. - The
animation-iteration-countis the number of times the animation plays; iteration means repeated iterations, and count means the number of times. So this property indicates the number of times the animation plays. The parameter can be 1, 2, 3, 4, 5... or infinite, indicating infinite repetition. - The
animation-play-stateis the playback state of the animation; paused means to pause, and running means to continue. - The
animation-fill-modeis the fill mode of the animation; forwards means to apply the last frame's settings, backwards means to apply the first frame's settings, which is generally the original settings rather than the first 0% of the animation frame, and both means both apply, which is similar to forwards.
2. Implementing a hover property#
- Keyframes hover animation implementation
.button {
cursor: pointer;
background-color: antiquewhite;
}
.button :hover {
animation-name: bgcolor;
animation-duration: 3s;
background-color: antiquewhite;
}
@keyframes bgcolor {
0% {
background-color: rgb(0, 140, 140);
}
100% {
background-color: rgb(208, 127, 29);
}
}
- Question: Why is the hover animation not implemented?
- Solution: Change
.button :hoverto.button:hover, as the issue lies in the.button :hoverselector. In CSS selectors,.button :hovermeans selecting any element inside.buttonwhen hovered, not the state of.buttonitself when hovered. This is because there is a space between.buttonand:hover, which represents a descendant selector, meaning it will select the hover state of the child elements of.button, not.buttonitself.
.button {
cursor: pointer;
background-color: antiquewhite;
}
.button:hover {
animation-name: bgcolor;
animation-duration: 3s;
background-color: antiquewhite;
animation-iteration-count: infinite;
}
@keyframes bgcolor {
0% {
background-color: rgb(0, 140, 140);
}
50% {
background-color: rgb(208, 127, 29);
}
100% {
background-color: rgb(0, 140, 140);
}
}
3. Implementing a click event#
Why is there no feedback when I click?
.button {
cursor: pointer;
background-color: antiquewhite;
}
.button:checked {
animation-name: bgcolor;
animation-duration: 3s;
background-color: antiquewhite;
animation-iteration-count: infinite;
}
@keyframes bgcolor {
0% {
background-color: rgb(0, 140, 140);
}
50% {
background-color: rgb(208, 127, 29);
}
100% {
background-color: rgb(0, 140, 140);
}
}
The problem lies in using the .button:checked selector, which is typically used for the checked state of form elements (like checkboxes, radio buttons, etc.), not for regular button elements. If your .button is a <button> or <div> element, the :checked pseudo-class selector is not applicable, so there will be no effect when clicked.
If you want to trigger an animation upon clicking the button, consider the following methods:
- Use JavaScript to add a class when the click event occurs, and then trigger the animation through that class.
- If you want immediate feedback on click (or touch), consider using the
:activepseudo-class. However, note that the:activestate only applies while the element is being activated (i.e., during the mouse press), and once the mouse is released, the element will immediately return to its normal state. - For buttons that can toggle states (like toggle buttons), you can use a hidden checkbox and label to achieve this. When the user clicks the label, it will change the checked state of the checkbox, allowing you to control the animation through the checkbox's
:checkedpseudo-class.
After changing to active, it is in the active state, but releasing the mouse will return to the original state. This means that while you keep the mouse pressed, it executes the animation, but releasing it will stop the execution.
This should not be called a click event; it should be called: hold event.
So how to implement click event animation?
.button {
cursor: pointer;
background-color: antiquewhite;
}
.animate {
animation-name: bgcolor;
animation-duration: 3s;
animation-iteration-count: infinite;
}
@keyframes bgcolor {
0% {
background-color: rgb(0, 140, 140);
}
50% {
background-color: rgb(208, 127, 29);
}
100% {
background-color: rgb(0, 140, 140);
}
}
document.getElementById('animatedButton').addEventListener('click', function() {
this.classList.add('animate');
});
4. Implementing other animation effects, such as rotation, scaling, moving, etc.#
The CSS transform property allows you to perform transformations such as moving, scaling, rotating, and skewing elements. Here are some commonly used transform functions:
-
Translation (Translate):
translate(x, y): Moves the element along the X and Y axes.translateX(x): Moves the element only along the X axis.translateY(y): Moves the element only along the Y axis.
.translate { transform: translate(50px, 100px); /* Move right 50px, down 100px */ } -
Scaling (Scale):
scale(x, y): Scales the element along the X and Y axes.scaleX(x): Scales the element only along the X axis.scaleY(y): Scales the element only along the Y axis.
.scale { transform: scale(2, 3); /* Width scaled by 2 times, height scaled by 3 times */ } -
Rotation (Rotate):
rotate(angle): Rotates the element, whereangleis the rotation angle, which can be indeg(degrees),rad(radians), etc.
.rotate { transform: rotate(45deg); /* Rotate clockwise by 45 degrees */ } -
Skewing (Skew):
skew(x-angle, y-angle): Skews the element along the X and Y axes.skewX(angle): Skews the element only along the X axis.skewY(angle): Skews the element only along the Y axis.
.skew { transform: skew(30deg, 20deg); /* Skew 30 degrees along the X axis, 20 degrees along the Y axis */ } -
Combining uses:
- The
transformproperty can combine multiple transformation functions, applying them to the element in the specified order.
.combine { transform: rotate(30deg) translate(100px, 50px) scale(1.5); }In this example, the element with the
.combineclass is first rotated by 30 degrees, then moved along the X and Y axes, and finally scaled by 1.5 times. - The
-
The
matrixtransformation in CSS is a very powerful transformation tool that can combine all 2D transformation effects (translation, rotation, scaling, skewing) through a 6-value matrix. This matrix is as follows:scaleX()andscaleY()represent the scaling ratios along the X and Y axes, respectively.skewX()andskewY()represent the skew angles along the X and Y axes, respectively.translateX()andtranslateY()represent the translation distances along the X and Y axes, respectively.matrix(scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY())
Using thematrixtransformation can achieve all 2D transformation effects, including translation, scaling, rotation, and skewing, but it is not intuitive and requires some mathematical knowledge to construct suitable matrix values.
However, it should be noted that thematrixtransformation itself is only applicable to 2D transformations; for 3D transformations (such as translation or rotation along the Z axis), you need to usematrix3dor other 3D transformation-related functions (such astranslateZ(),rotateX(),rotateY(),rotateZ(),perspective(), etc.). Therefore, if your question is whethermatrixcan handle 3D transformations, the answer is no. For 3D transformations, you should usematrix3dor combine other 3D transformation functions.
Using the transform property allows you to visually transform elements without affecting the layout of the page, making it a powerful tool for achieving complex animations and layout effects. Additionally, transform is often used in conjunction with the transition or animation properties to achieve smooth transition effects.
.
.button {
cursor: pointer;
background-color: antiquewhite;
}
.button:active {
animation-name: bgcolor;
animation-duration: 3s;
background-color: antiquewhite;
animation-iteration-count: infinite;
}
.button:hover {
animation-name: aaa;
animation-duration: 3s;
background-color: antiquewhite;
animation-iteration-count: infinite;
}
@keyframes bgcolor {
form {
transform: rotate(32deg);
}
to {
transform: rotate(90deg);
}
}
@keyframes aaa2 {
form {
transform: scale(1);
}
to {
transform: scale(2);
}
}
@keyframes aa21a {
form {
transform: skew(2deg);
}
to {
transform: skew(60deg);
}
}
@keyframes aaa {
form {
transform: translate(0px, 0px);
}
to {
transform: translate(0px, 250px);
}
}
5. Gradient transition animation effects#
- Transition to achieve gradient animation
.button {
width: 20px;
cursor: pointer;
transform: none;
transition-property: transform width;
transition-duration: 2s;
background-color: antiquewhite;
}
.button:hover {
width: 230px;
transform: rotate(49deg);
}
- Transform transition animation
.button {
cursor: pointer;
transform: none;
transition: 2s;
background-color: antiquewhite;
}
.button:hover {
transform: rotate(49deg);
}
They are essentially both gradient animations achieved through transition. Transform is just a part of the CSS properties.
6. Constructing @keyframes animations:#
- Use JavaScript to construct a complete
@keyframesanimation and insert it into the document's<style>tag. - Example:
var duration = '2s'; var fromPosition = '-100%'; var toPosition = '0'; var styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; styleSheet.innerHTML = `@keyframes dynamicSlideIn { from { transform: translateX(${fromPosition}); } to { transform: translateX(${toPosition}); } }`; document.head.appendChild(styleSheet); var elem = document.getElementById('myElement'); elem.style.animationName = 'dynamicSlideIn'; elem.style.animationDuration = duration; elem.style.animationFillMode = 'forwards';