banner
Jrenc

Jrenc

There’s a million things I haven’t done。
x
github
email
bilibili

CSS Animation Implementation

Animation API#

Creating animations in CSS mainly relies on the following key APIs:

  1. @keyframes rule

    • Used to define the intermediate steps (keyframes) of an animation. In the @keyframes rule, 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 @keyframes rule trigger?

    • When an element is bound to the animation-name property, the keyframes defined in the @keyframes rule will be executed according to the specified timing and speed curve when the animation starts.
    • For example, the above example animation will be executed according to the settings of the animation-duration and animation-timing-function properties after being bound to an element in the animation-name property.
  2. animation-name property

    • Specifies the @keyframes name that needs to be bound to the selector.
    .element {
      animation-name: example;
    }
    
  3. animation-duration property

    • Defines the time it takes to complete one cycle of the animation, such as seconds or milliseconds.
    .element {
      animation-duration: 2s;
    }
    
  4. animation-timing-function property

    • Defines the speed curve of the animation, such as linear, ease, ease-in, ease-out, ease-in-out, or cubic-bezier functions.
    .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:

    1. 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.
    2. 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.
    3. 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.
    4. 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.
    5. 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-in and ease-out, suitable for scenes that require a smooth transition.
    6. cubic-bezier(n,n,n,n)

      • Allows you to customize a speed curve. The cubic-bezier function accepts four parameters that define a cubic Bezier curve, allowing precise control over the acceleration and deceleration of the animation. CSS provides a cubic-bezier tool 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
  5. animation-delay property

    • Sets the delay time before the animation starts.
    .element {
      animation-delay: 1s;
    }
    
  6. animation-iteration-count property

    • Defines how many times the animation should play, which can be a number or infinite to indicate infinite repetition.
    .element {
      animation-iteration-count: infinite;
    }
    
  7. animation-direction property

    • Specifies whether the animation should play in reverse on alternate cycles. Common values include normal, reverse, alternate, alternate-reverse.
    .element {
      animation-direction: alternate;
    }
    
  8. animation-fill-mode property

    • Specifies how styles should be applied to the target element before and after the animation executes. For example, forwards retains the styles of the last keyframe.
    .element {
      animation-fill-mode: forwards;
    }
    

    The animation-fill-mode property 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. The animation-fill-mode property accepts the following values:

    1. 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.
    2. 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.
    3. 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.
    4. both
      • The animation follows the rules of forwards and backwards, 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.

    For example, if you have a fade-out animation, you might want the element to remain transparent after the animation ends.

  9. animation shorthand property

    • You can use the animation shorthand property to set all animation properties at once.
    .element {
      animation: example 2s infinite ease-in-out;
    }
    
  10. animation-play-state property

    • Controls the playback state of the animation. It can be set to paused to pause the animation or running to continue playing the animation.
    .element {
      animation-play-state: paused;
    }
    
  11. 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);
    }
    
  12. Using @media queries 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;
      }
    }
    
  13. will-change property

    • 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;
    }
    
  14. Using CSS animations for performance optimization

    • Whenever possible, use transform and opacity animations, as they can be hardware accelerated, improving animation performance.
  15. 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, and animationiteration to execute scripts at different stages of the animation.
    document.querySelector('.element').addEventListener('animationend', function() {
      console.log('Animation ended');
    });
    

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-name property 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-duration property indicates the duration of the animation;
  • The animation-delay property indicates the delay time of the animation;
  • The animation-timing-function is 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-count is 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-state is the playback state of the animation; paused means to pause, and running means to continue.
  • The animation-fill-mode is 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 :hover to .button:hover, as the issue lies in the .button :hover selector. In CSS selectors, .button :hover means selecting any element inside .button when hovered, not the state of .button itself when hovered. This is because there is a space between .button and :hover, which represents a descendant selector, meaning it will select the hover state of the child elements of .button, not .button itself.
.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:

  1. Use JavaScript to add a class when the click event occurs, and then trigger the animation through that class.
  2. If you want immediate feedback on click (or touch), consider using the :active pseudo-class. However, note that the :active state 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.
  3. 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 :checked pseudo-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:

  1. 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 */
    }
    
  2. 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 */
    }
    
  3. Rotation (Rotate):

    • rotate(angle): Rotates the element, where angle is the rotation angle, which can be in deg (degrees), rad (radians), etc.
    .rotate {
      transform: rotate(45deg); /* Rotate clockwise by 45 degrees */
    }
    
  4. 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 */
    }
    
  5. Combining uses:

    • The transform property 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 .combine class is first rotated by 30 degrees, then moved along the X and Y axes, and finally scaled by 1.5 times.

  6. The matrix transformation 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() and scaleY() represent the scaling ratios along the X and Y axes, respectively.
    • skewX() and skewY() represent the skew angles along the X and Y axes, respectively.
    • translateX() and translateY() represent the translation distances along the X and Y axes, respectively.
    • matrix(scaleX(), skewY(), skewX(), scaleY(), translateX(), translateY())
      Using the matrix transformation 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 the matrix transformation itself is only applicable to 2D transformations; for 3D transformations (such as translation or rotation along the Z axis), you need to use matrix3d or other 3D transformation-related functions (such as translateZ(), rotateX(), rotateY(), rotateZ(), perspective(), etc.). Therefore, if your question is whether matrix can handle 3D transformations, the answer is no. For 3D transformations, you should use matrix3d or 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 @keyframes animation 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';
    
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.