CSS for Web Development

0% completed

Previous
Next
Keyframes

Keyframes allow you to define the stages of an animation. With keyframes, you can control how an element's properties change over time. By setting values at specific points, you create smooth, custom animations that run from start to finish.

Keyframes are defined using the @keyframes rule, where you specify different states of the element during the animation.

Syntax

@keyframes animation-name { /* Define the animation's stages as percentages or keywords */ 0% { property: value; } 50% { property: value; } 100% { property: value; } } /* Applying the animation to an element */ selector { animation-name: animation-name; animation-duration: duration; animation-timing-function: timing-function; /* Other animation properties can be added as needed */ }

Explanation:

  • @keyframes animation-name:
    • This rule defines the steps of the animation.
    • Use percentages (0%, 50%, 100%) or keywords like from and to to mark points along the animation timeline.
  • animation-name:
    • Tells the element which keyframes to use.
  • animation-duration:
    • Specifies how long the animation runs.
  • animation-timing-function:
    • Controls the speed curve of the animation (e.g., linear, ease, ease-in, ease-out).

Example 1: Simple Color Change Animation

In this example, a box changes its background color gradually using keyframes. The animation starts with a light blue background and ends with a light green background.

HTML

. . . .

Explanation:

  • Keyframes Definition:
    • The @keyframes colorChange rule changes the background color from light blue (0%) to light green (100%).
  • Animation Properties:
    • The .animated-box uses the keyframes over a period of 3 seconds with an ease-in-out timing.
  • Outcome:
    • The box gradually changes its background color in a smooth animation from start to finish.

Example 2: Moving an Element Across the Screen

This example shows an animation that moves a box from the left side of the screen to the right side and then back. This is done by changing its transform property using keyframes.

HTML

. . . .

Explanation:

  • Keyframes Definition:
    • @keyframes slide moves the box from its starting position (0%), to 300px to the right at 50%, then back to the start at 100%.
  • Animation Properties:
    • The .sliding-box is animated over 4 seconds with an ease-in-out timing function.
    • The animation repeats indefinitely (using infinite).
  • Outcome:
    • The box smoothly slides to the right and returns to its original position continuously, demonstrating a looping motion.

These examples illustrate how to implement keyframe animations for both simple style transitions and more complex movements, providing a powerful tool to make your web pages dynamic and engaging.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next