Bouncing Ball Animation: Simple CSS Code with Explanation

Learn how to create a simple bouncing ball animation using CSS. This beginner-friendly tutorial will guide you through the code and its functionality.



Code Snippets

1. HTML (index.html)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bouncing Ball Animation</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="ball"></div>

    <h2>Try the Bouncing Ball Animation!</h2>
    <p>The animation will make the ball bounce up and down.</p>
</body>
</html>

2. CSS (styles.css)


/* Resetting margin and padding for a clean slate */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Body styling */
body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    text-align: center;
    flex-direction: column;
}

/* The bouncing ball */
.ball {
    width: 50px;
    height: 50px;
    background-color: red;
    border-radius: 50%;
    animation: bounce 1s infinite;
}

/* Keyframes for bouncing animation */
@keyframes bounce {
    0%, 100% {
        transform: translateY(0);
    }
    50% {
        transform: translateY(-50px);
    }
}


Explanation

  • @keyframes bounce: Defines the animation's behavior. It specifies that at 0% and 100% of the animation, the ball is at its original position, and at 50%, it moves upward by 50px.
  • .ball: This class applies the animation to an element. The animation repeats infinitely with a 1-second duration.

How it Works:

  • HTML: Contains a div with the class ball, which will be animated. It also includes a title and description to explain the animation.
  • CSS:
    • The @keyframes rule defines the bounce animation.
    • The .ball class applies styles to the ball (size, color, and the bounce animation).
    • The animation is set to run indefinitely with infinite.

Instructions to Use:

  1. Create two files: One for HTML (e.g., index.html) and one for CSS (e.g., styles.css).
  2. Link them: Make sure the HTML file links to the CSS file using the <link rel="stylesheet" href="styles.css"> tag in the <head> section.
  3. Open the HTML file: Open index.html in a browser to see the bouncing ball animation in action.

Try It Yourself

Copy the code above and paste it into your HTML or CSS editor to experiment with the animation. You can change the bounce height or speed to make it your own!

Demo

Check out the animation in action: View on Instagram

Comments

Popular posts from this blog

Infinite Scroll Animation

3D Glowing Bottle HTML CSS