CSS transitions allow us to animate the change of a property value over a specified duration. For example, you can smoothly change the background color or font size of an element when a user hovers over it. Here's a simple example:
In this example, when the user hovers over a button, its background color will transition from blue to green in 0.5 seconds.
CSS Keyframe Animations
For more complex animations, we can use CSS keyframes. Keyframes allow us to define the state of an element at different points during an animation. By specifying keyframes, we can create multi-step animations. Here's an example of a simple keyframe animation that rotates a square:
In this example, we define a keyframe animation called
rotateSquare. At the beginning of the animation (0%), the square is not rotated (0 degrees). At the end of the animation (100%), it's rotated by 360 degrees. The square element uses this animation, taking 2 seconds to complete one rotation and repeating indefinitely.
We've covered simple animations, but what if we want to make them interactive? We can do this using the power of CSS pseudo-classes. For example, let's create an interactive card flip animation:
In this example, we create a card element with two sides:
.card-back. When the user hovers over the card, the
.card-inner element rotates 180 degrees on the Y-axis, revealing the other side of the card. The transition creates a smooth flip animation.
How can I create simple animations with CSS?
You can create simple animations using CSS transitions by specifying the property, duration, and optionally, the easing function and delay.
What if I want to create more complex animations?
For more complex animations, you can use CSS keyframes, which allow you to define the state of an element at different points during an animation.
How can I make my animations interactive?
To create interactive animations, you can use CSS pseudo-classes like
:focus, combined with transitions or keyframes. This allows you to trigger animations based on user interactions.