Animated ball using CSS and HTML

Posted: 26-06-18

With the death of flash I thought it would be a cool idea if I could make some realistic animations using just CSS and HTML. Stuff like this has long been possible using JavaScript and jQuery but I figured you could make a more elegant solution using the animation properties in CSS

How it works

First things first I needed a ball. This was created using the border-radius property. I then added a gradient fill and a inner shadow to give the ball a 3D appearance. Once I had the ball looking like it should I started working on the animation. It's pretty easy to make a ball bounce, but to make it realistic you need to spend a bit of time looking at the easing functions. In the end I used a custom cubic-bezier curve, this allows the ball to slow at the top of the animation, and again at the bottom. The standard easing functions just aren't up to the job so the bezier is really the only way to go. I separated the animation into two different divs, one for the bounce and another for it's travel back and forth across the page. The travelling div only requires a simple linear easing, but combined with the bouncing ball it gives a great effect. It also allows you to change the speed of travel without affecting any other aspects of the animation.

Adding the realism

So now, the ball bounced and moved across the screen. Not bad, but not quite right yet. I needed the ball to squash a bit as it hit the bottom, and then stretch a bit as it went back up/down. This was achieved simply by using CSS transforms and the @keyframes functionality. It took a bit of playing around to get it just right but I was very happy with the final result. The final part was to add an animated shadow that would grow and shrink to match the balls position. I created an ellipse (using border-radius again), added a blur and reduced it's opacity. Then, matching the balls keyframes, adjusted the sizes and opacity to give a realistic shadow. That's about all there is to it. You can check out the example by visiting my codepen page. Feel free to mess around with the values. I think the next iteration will use Sass or some other CSS preprocessor because changing certain values will mess it up and I think it could be made more robust.