30/10/2024
Creating animations on the web can elevate user experience and make your designs more dynamic. CSS animations allow you to animate transitions between different CSS styles. One of the most powerful ways to create animations in CSS is by using keyframes. Here's a step-by-step guide on how to create custom animations using keyframes.
To get started, you'll need an HTML element to animate. Here’s a simple example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Keyframe Animation Example</title> </head> <body> <div class="box"></div> </body> </html>
In this case, we’ve created a <div>
with the class box
, which is what we’ll animate.
Next, let's add some styles to our box in a separate CSS file (e.g., styles.css
):
body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .box { width: 100px; height: 100px; background-color: #3498db; }
We’re styling the body to center our box and giving our box a width, height, and a background color.
Keyframes are like a storyboard for your animation. You define the start and end points of the animation, as well as any intermediate steps.
Here's how you can define keyframes for our animation:
@keyframes slide { 0% { transform: translateX(0); opacity: 0; } 50% { transform: translateX(50px); opacity: 1; } 100% { transform: translateX(100px); opacity: 0; } }
In this @keyframes
rule:
0%
defines the start of the animation with the box in its original position and transparent.50%
moves the box to the right by 50 pixels and makes it fully visible.100%
moves the box further to the right (100 pixels total) while fading it out.Now that you've defined your keyframes, apply them to the .box
class:
.box { width: 100px; height: 100px; background-color: #3498db; animation: slide 2s ease-in-out infinite; }
Here’s what’s happening:
animation: slide
: This tells the browser to use the slide
keyframe animation.2s
: This is the duration of the animation, meaning it will complete one cycle in 2 seconds.ease-in-out
: This sets how the animation accelerates and decelerates.infinite
: This makes the animation repeat indefinitely.To see your animation in action, simply open your HTML file in a web browser. You should see your blue box smoothly sliding across the screen, appearing and disappearing as it moves.
linear
, ease
, ease-out
, etc., to see how they affect your animation.animation-delay: 1s;
.background-color
, width
, height
, and more!By following these steps and experimenting with the different properties, you can create engaging animations that enhance your web projects. Dive in, and start playing around with keyframes to see what stunning visuals you can create!
30/10/2024 | CSS
30/10/2024 | CSS
30/10/2024 | CSS
30/10/2024 | CSS
30/10/2024 | CSS
30/10/2024 | CSS
30/10/2024 | CSS