CSS3 Bouncing Balls

CSS3AnimationExperiments

Making balls bounce using only CSS3 animations without JavaScript

CSS3 Bouncing Balls

We have had a lot of fun making balls bounce off walls in HTML5 Canvas or even just by using DIVs and some JavaScript code.

So now I have set myself up for a challenge to make it happen without using JavaScript but using CSS3 alone.

Of course animations can be done pretty easily using CSS3. But it is not possible to check for collisions and wall impacts.
So I had to think differently.

I started off by making a div (ball) bounce Vertically. That's fairly simple in CSS3, ain't it?

The Basic Implementation

.ball {
  width: 50px;
  height: 50px;
  background-color: #f00;
  border-radius: 50%;
  position: absolute;
  animation: bounce 2s infinite;
}

@keyframes bounce {
  0%, 100% {
    bottom: 0;
    animation-timing-function: ease-out;
  }
  50% {
    bottom: 200px;
    animation-timing-function: ease-in;
  }
}

Adding More Complexity

The challenge gets interesting when you want to make multiple balls bounce in different directions without any JavaScript logic. Here's how I approached it:

  1. Use separate animations for horizontal and vertical movement
  2. Set different animation durations for each ball
  3. Use animation-delay to create a more random feeling

Demo

You can see this in action in the codepen below (recreated from the original):

Limitations

Without JavaScript, there are some limitations:

  • No real collision detection
  • Predetermined animation paths
  • No interaction with user input

However, it's a fun CSS3 experiment that shows what's possible with pure CSS animations!

Conclusion

While this approach doesn't replace JavaScript for complex animations with real physics, it demonstrates how powerful CSS3 animations can be for creating engaging visual effects with minimal code.

Note: This article was migrated from the original A thousand nodes blog (2012)

Continue Reading

Browse All Articles